Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting DataContext with SelectedItem Programmatically

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

More simply, how do you reproduce this type of binding in code?

<StackPanel>
    <ListBox Name="listBox1" />
    <TextBox Name="textBox1" DataContext="{Binding ElementName=listBox1, Path=SelectedItem}" />
</StackPanel>
like image 513
Toji Avatar asked Mar 02 '23 05:03

Toji


2 Answers

You need to set a Name for the textbox so you can refer to it in code. Then you should just be able to assign an object to the DataContext property. You can create a data binding programatically like so:

Binding binding = new Binding();
binding.ElementName = "listBox1";
binding.Path = new PropertyPath("SelectedItem");
binding.Mode = BindingMode.OneWay;
txtMyTextBox.SetBinding(TextBox.TextProperty, binding);
like image 153
Ty. Avatar answered Mar 04 '23 09:03

Ty.


Wow, sometimes you just have to spell the question out to get that extra nudge 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);
like image 39
Toji Avatar answered Mar 04 '23 11:03

Toji