以编程方式使用SelectedItem设置DataContext



如何以编程方式设置指定列表中所选项目的DataContext?

更简单地说,如何在代码中重现这种类型的绑定?

<StackPanel>
    <ListBox Name="listBox1" />
    <TextBox Name="textBox1" DataContext="{Binding ElementName=listBox1, Path=SelectedItem}" />
</StackPanel>

您需要为文本框设置一个名称,以便在代码中引用它。然后,您应该能够将一个对象分配给DataContext属性。您可以通过程序创建数据绑定,如下所示:

Binding binding = new Binding();
binding.ElementName = "listBox1";
binding.Path = new PropertyPath("SelectedItem");
binding.Mode = BindingMode.OneWay;
txtMyTextBox.SetBinding(TextBox.TextProperty, binding);

哇,有时你只需要把问题拼出来,就能把它推向正确的方向,是吗?

这个代码对我有效:

Binding b = new Binding();
b.Path = new PropertyPath(ListBox.SelectedItemProperty);
b.Source = listBox1;
textBox1.SetBinding(TextBox.DataContextProperty, b);

最新更新