你如何绑定到用户控件的属性? [英] How do you bind to the property of a User Control?
问题描述
在Windows应用商店的应用程序,您可以创建一个用户控件封装和重用代码隐藏和布局XAML。一个简单的用户控件可能是这样的:
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>
现在,我想设置绑定。所以我创建的代码隐藏与暴露UI控件的Text属性的属性。事情是这样的:
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; }
}
不过,这是行不通的。这似乎是数据绑定到用户控件是一个XAML UI中有价值的一部分。但它是如何实现的?
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?
推荐答案
有只有一个用户控件实现一个属性,它支持在方页面绑定。这是一个依赖项属性。实现是很简单的,但你也必须包括更改事件直接与UI交互,因为一个依赖属性是一个控制的静态属性。像这样的:
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();
}
我承认,这不是超级明显。但希望现在你知道,这将节省您在搜索,并试图弄清楚小时。同样,你只能绑定到用户控件的依赖属性。而且,您可以只设置UI值的时候使用更改事件的静态线程。
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.
祝你好运!
这篇关于你如何绑定到用户控件的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!