Goal: Bind in XAML to an object created in code behind.
Problem: Binding doesn't work.
Notes:
1. It works, if the object is created in XAML.
2. RegisterName is used.
Question: How to bind in XAML to an object created in code behind in the way illustrated in the following example?
MainWindow.xaml:
<StackPanel x:Name="stackPanel" Background="Black" MouseDown="StackPanel_MouseDown"><TextBox x:Name="textBox" Text="{Binding ElementName=ok, Path=Text, Mode=OneWay}"/></StackPanel>MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void StackPanel_MouseDown(object sender, MouseButtonEventArgs e)
{
TextBox textBox = new TextBox();
this.RegisterName("ok", textBox);
stackPanel.Children.Add(textBox);
}
}