How do you bind to the property of a User Control?

不羁的心 提交于 2020-02-27 02:26:17

问题


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

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

Now, I want to setup binding. So I create code-behind with properties that expose the Text properties of the UI controls. Something like this:

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

However, this does not work. It seems like data binding to a user control is a valuable part of a XAML UI. But how is it accomplished?


回答1:


There is only one implementation of a property in a user control that supports binding in the consuming page. That is a dependency property. The implementation is simple enough, but you must also include the changed event to interact directly with the UI, since a dependency property is a static property on a 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, this is not super obvious. But hopefully now that you know, it will save you hours of searching and trying to figure out. Again, you can only bind to a dependency property of a user control. And, you can only set the UI values off the static thread using the changed event.

Best of luck!




回答2:


You always talk about binding - but you don't actually bind the textbox.textproperty to your property (you set it).

If you wanna use binding, create a dependency property and bind the text-property of the textbox this way:

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

Don't forget to set the usercontrols DataContext property to the usercontrol-instance:

public MyUserControl1()
{
  this.InitializeComponent();

  // Set the datacontext to the usercontrol-instance.
  // If you don't, the binding will use the usercontrol's parent-datacontext.
  this.DataContext = this;
}


来源:https://stackoverflow.com/questions/16573819/how-do-you-bind-to-the-property-of-a-user-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!