user904567
user904567

Reputation: 67

Dynamically change the WPF Datagrid column header

I am using wpf toolkit datagrid in wpf win applications. In my view model, I have a observablecollection property which is binded to the itemsource of the datagrid. Student class is having Name, Age, Class properties and displays in each columns in the grid.

But I have a property called "Header1" in my View model class and how i can bind it to the Header of the data grid text column ? When I used, it is not displaying the header string in the grid. I need to update this column header at run time. How I can do that ? I also tried the following way;

<dg:DataGridColumn Header = "{Binding Header1, ElementName=MyUsrCtrl}" />

BUT this is also not working ? I used DataContext.Header1, ElementName=MyUsrCtrl also...but no use.

How it is possible ?

Upvotes: 3

Views: 6075

Answers (2)

Vinit Sankhe
Vinit Sankhe

Reputation: 19895

You cannot bind to any daatgrid columns as they are not part of the visual tree. Use the proxy element trick.

WPF Error: Cannot find governing FrameworkElement for target element

Upvotes: 2

Zann Anderson
Zann Anderson

Reputation: 4907

Without knowing much about your code, I'm just taking a stab at this, but here we go. I'm assuming you've bound your entire view to your view model using DataContext, and that you're binding ItemsSource for the DataGrid something like this:

<dg:DataGrid ItemsSource="{Binding MyCollection}" />

Assuming that's true, you're most of the way there with your header binding. Just remove the ElementName portion of the binding like so:

<dg:DataGridColumn Header = "{Binding Header1}" />

That should do the trick. One other thing to note is to make sure that your view model implements INotifyPropertyChanged and that the setter for the Header1 property calls your PropertyChanged method for itself.

Upvotes: -1

Related Questions