且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

你如何绑定到用户控件的属性?

更新时间:2021-09-26 18:51:01

有只有一个用户控件实现一个属性,它支持在方页面绑定。这是一个依赖项属性。实现是很简单的,但你也必须包括更改事件直接与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.

祝你好运!