Configuring a DataContext with SelectedItem Programatically

How do you programmatically set a DataContext that indicates the selected list item?

Simply put, how do you reproduce this type of binding in code?

<StackPanel> <ListBox Name="listBox1" /> <TextBox Name="textBox1" DataContext="{Binding ElementName=listBox1, Path=SelectedItem}" /> </StackPanel> 
+4
source share
2 answers

You need to set a name for the text field so that you can refer to it in the code. Then you just have to assign the object to the DataContext property. You can create data binding tactically:

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

Wow, sometimes you just need to ask a question to get an extra push in the right direction, huh?

This code works for me:

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

All Articles