How do you bind to the User Control property?

In Windows Store apps, you create a user control to encapsulate and reuse XAML code and layout. A simple user control might look like this:

<UserControl> <StackPanel> <TextBlock Text="First Name" /> <TextBox x:Name="MyTextBox" /> </StackPanel> </UserControl> 

Now I want to configure the binding. Therefore, I am creating code with properties that display the text properties of the user interface controls. Something like that:

 public string TextBoxText { get { return MyTextBoxText.Text; } set { MyTextBoxText.Text = value; } } 

However, this does not work. Binding data to a user control appears to be an important part of the XAML interface. But how is this done?

+4
source share
2 answers

There is only one property implementation in a user control that supports binding on the consumption page. This is a dependency property. The implementation is quite simple, but you must also include the changed event to interact directly with the user interface, since the dependency property is a static property of the control. Like this:

 public string TextBoxText { get { return (string)GetValue(TextBoxTextProperty); } set { SetValue(TextBoxTextProperty, value); } } public static readonly DependencyProperty TextBoxTextProperty = DependencyProperty.Register("TextBoxText", typeof(string), typeof(MyUserControl), new PropertyMetadata(string.Empty, OnTextBoxTextPropertyChanged)); private static void OnTextBoxTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { (d as MyUserControl).MyTextBox.Text = e.NewValue.ToString(); } 

I admit that this is not too obvious. But, hopefully, now that you know this, it will save you hours of searching and trying to find out. Again, you can only bind to the dependency property of the user control. And you can only set user interface values ​​from a static stream with a modified event.

Good luck

+10
source

You always talk about binding, but you really don't bind textbox.textproperty to a property (you set it).

If you want to use binding, create a dependency property and bind the text property of the text field as follows:

 <TextBox x:Name="MyTextBox" **Text="{Binding TextBoxText, Mode=TwoWay}"** /> 

Remember to set the usercontrols DataContext property to usercontrol-instance:

 public MyUserControl1() { this.InitializeComponent(); // Set the datacontext to the usercontrol-instance. // If you don't, the binding will use the usercontrol parent-datacontext. this.DataContext = this; } 
0
source

Source: https://habr.com/ru/post/1481026/


All Articles