0

I am trying to set the binding for a Data Grid Column Headers text during the Auto generating Column event but with no luck. headerDetails is a dictionary containing columnSettings objects that implement the INotifyPropertyChanged interface (Header setter raises an OnPropertyChanged event)

private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    e.Column.Header = this.headerDetails[headername].Header;
    //// rather than set the value here, create a binding
}

I have tried looking at these examples mentioned and came up with this:

Binding myBinding = new Binding();
myBinding.Source = this.headerDetails[headername].Header;
myBinding.Path = new PropertyPath("Header");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(e.Column, TextBox.TextProperty, myBinding);

which unfortunately doesn't work :(

MM8 answer has fixed the problem thanks, I was Binding to the variable rather than the object. the solution with notes:

Binding myBinding = new Binding();                            
myBinding.Source = this.headerDetails[headername];           // Source = object
myBinding.Path = new PropertyPath("Header");                 // Path = Getter/Setter
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(e.Column, DataGridTextColumn.HeaderProperty, myBinding);
3
  • Possible duplicate of How to set a binding in Code? Commented Jun 19, 2017 at 11:07
  • Ofcourse, there are also other duplicates if you don't like the one I mentioned first... stackoverflow.com/questions/2368479/wpf-data-binding-with-code for example. Commented Jun 19, 2017 at 11:09
  • are you sure that the class stored in the dictionary implement INotifyPropertyChanged ? (for example public myClass : INotifyPropertyChanged). Plus you should remove ".Header" from the source Commented Jun 19, 2017 at 13:20

1 Answer 1

1

You should set the Source property of the Binding to the object that implements the INotifyPropertyChanged interface:

Binding myBinding = new Binding();
myBinding.Source = this.headerDetails[headername];
myBinding.Path = new PropertyPath("Header");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(e.Column, DataGridTextColumn.HeaderProperty, myBinding);

This should work provided that headerDetails[headername] returns an INotifyPropertyChanged and that you then set the Header property of this very same instance.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.