如何以编程方式设置指定列表中所选项的DataContext?
更简单地说,如何在代码中重现这种类型的绑定?
<StackPanel>
<ListBox Name="listBox1" />
<TextBox Name="textBox1" DataContext="{Binding ElementName=listBox1, Path=SelectedItem}" />
</StackPanel>
答案 0 :(得分:7)
您需要为文本框设置名称,以便在代码中引用它。然后,您应该只能将对象分配给DataContext属性。您可以以编程方式创建数据绑定:
Binding binding = new Binding();
binding.ElementName = "listBox1";
binding.Path = new PropertyPath("SelectedItem");
binding.Mode = BindingMode.OneWay;
txtMyTextBox.SetBinding(TextBox.TextProperty, binding);
答案 1 :(得分:1)
此代码适用于我:
Binding b = new Binding();
b.Path = new PropertyPath(ListBox.SelectedItemProperty);
b.Source = listBox1;
textBox1.SetBinding(TextBox.DataContextProperty, b);