简体   繁体   中英

Bind DataGrid Headers Text to properties in WPF MVVM at runtime

I have a datagrid whose column headers I would like to change during runtime. I have tried something like this but doesn't work

    <DatagridTextColumn Header="{Binding Path=MyNewHeader}" Binding=" {Binding Path=MyBindingProperty}" />

And In my MVVM

    string myHeaderProperty;
    public string MyHeaderProperty{
    get{
    return myHeaderProperty 
    }
    set{
    Set(ref myHeaderProperty, value);
    }

But does not work. Any Ideas will be greatly appreciated

If you take a look in the output window you will see that you probably get a binding expression exception because MyNewHeader is not a property on you item in the row.

So you need to bind it to the parent via relativesource binding

Take a look at the following example https://wpftutorial.net/BindingExpressions.html

This should work provided that MyHeaderProperty belongs to the DataContext of the parent DataGrid , ie the view model:

<DataGridTextColumn Binding="{Binding MyBindingProperty}">
    <DataGridTextColumn.HeaderTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=DataContext.MyHeaderProperty, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
        </DataTemplate>
    </DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM