How do I specify a control as a property in my user control in WPF?
-
03-07-2019 - |
Question
My XAML:
<TextBox x:Name="myTextBox" .../>
<MyExtender TargetTextBox=? .../>
My C#:
MyExtender : UserControl
{
public TargetTextBox { get; set; }
}
How do I set the TargetTextBox property in XAML?
Solution
You should be able to do:
<TextBox Name="tb">Something</TextBox>
<my:MyExtender TargetTextBox="{Binding ElementName=tb}" />
but this requires TargetTextBox to be a DependencyProperty. Change MyExtender.xaml.cs to:
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); }
}
}
And you should be set.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow