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);
stuicidle
  • 297
  • 1
  • 8
  • Possible duplicate of [How to set a binding in Code?](https://stackoverflow.com/questions/7525185/how-to-set-a-binding-in-code) – grek40 Jun 19 '17 at 11:07
  • Ofcourse, there are also other duplicates if you don't like the one I mentioned first... https://stackoverflow.com/questions/2368479/wpf-data-binding-with-code for example. – grek40 Jun 19 '17 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 – Daniele Sartori Jun 19 '17 at 13:20

1 Answers1

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.

mm8
  • 163,881
  • 10
  • 57
  • 88