如何在WPF中的用户控件中将控件指定为属性?

时间:2009-03-04 18:48:53

标签: wpf-controls

我的XAML:

<TextBox x:Name="myTextBox" .../>
<MyExtender TargetTextBox=? .../>

我的C#:

MyExtender : UserControl
{
    public TargetTextBox { get; set; }
}

如何在XAML中设置TargetTextBox属性?

1 个答案:

答案 0 :(得分:0)

你应该可以这样做:

<TextBox Name="tb">Something</TextBox>
<my:MyExtender TargetTextBox="{Binding ElementName=tb}" />

但这需要TargetTextBox为DependencyProperty。将MyExtender.xaml.cs更改为:

 public partial class MyExtender : System.Windows.Controls.UserControl
{
    public MyExtender()
    {
        InitializeComponent();
    }
    public static readonly DependencyProperty TargetTextBoxPropery = 
        DependencyProperty.Register("TargetTextBox", typeof(TextBox), typeof(MyExtender));

    public TextBox TargetTextBox
    {
        get { return (TextBox)GetValue(TargetTextBoxPropery); }
        set { SetValue(TargetTextBoxPropery, value); }
    }

}

你应该被设定。