Question

I'm trying to create a custom control which inherits from a TextBox control. in the constructor of my custom control I need to have the text property bound. this the code I'm using by now.

var binding = new Binding("Name");
binding.Mode = BindingMode.TwoWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
binding.ValidatesOnDataErrors = true;
SetValue(TextProperty, binding);

I haven't set a source for binding because I want it be the DataContext of the form on which my custom control will be placed however I suppose I'm doing it in a wrong way because when I added on the form I face the error message in xaml which says: "System.Windows.Data.Binding is not a valid value for property text.

Was it helpful?

Solution

Its not good to do in code-behind, hope this answers your question

Binding binding = new Binding();
binding.Path = new PropertyPath("yourPropertyTobeBinded");
binding.Source = sourceObject;
BindingOperations.SetBinding(youTextBox, TextBox.TextProperty, binding);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top