In WPF, three things are needed for a binding:
- A target
- A source
- A
Binding
It doesn't matter if you are doing this in XAML or in the code behind file, the concept is the same. In your case the target is the text property of
TextBox Mytextbox
, and the source is a single property of the selected item in you data grid.
To set the binding, we create an instance of the Binding class; set its Mode to TwoWay. We then set the source of the binding. We'll do this be telling the binding to look for a control with the name [information wasn't given in question]. This name should be the one in the DataGrid's x:Name property. Instead of targeting a cell in the DataGrid, we target the property you want from the item that is selected. We then finish this off by setting the binding to the TextBox's TextProperty attribute.
Binding b = new Binding();
b.Mode = BindingMode.TwoWay;
b.Path = new PropertyPath("SelectedValue.[The MyClass property I'm binding too]");
b.ElementName = "The x:Name of the datagrid.";
Mytextbox.SetBinding(TextBox.TextProperty, b);
Removing a one way binding can be done by setting a value on the target, but this doesn't work on a two way binding. So instead, I would advise you to set a one way binding to a property that doesn't exist, and disable the textbox.
Binding b = new Binding();
b.Mode = BindingMode.OneWay;
b.Path = "FakeProperty";
MyTextbox.SetBinding(TextBox.TextProperty, b);
MyTextbox.IsEnabled = false;