简体   繁体   English

如何将列 header 绑定到 ViewModel 中的属性? (WPF MVVM)

[英]How to bind column header to property in ViewModel? (WPF MVVM)

I Have window that have DataContext that is bind to ViewModel object (VM1 for the example).我有 window,它的 DataContext 绑定到 ViewModel object(例如 VM1)。 VM1 have a lot of properties and one of them is a string that called "MyTitle". VM1 有很多属性,其中之一是一个名为“MyTitle”的字符串。

I have a DataGridTextColumn in 'Window\Grid\DataGrid'.我在“Window\Grid\DataGrid”中有一个 DataGridTextColumn。 How can I bind the property "Header" in DataGridTextColumn to the Property "MyTitle" in my VM1 ViewModel?如何将 DataGridTextColumn 中的属性“Header”绑定到我的 VM1 ViewModel 中的属性“MyTitle”?

Thanks!谢谢!

Unfortunately, the column definitions of the DataGrid don't inherit the DataContext , because they're not part of the visual tree, so you can't bind directly to the ViewModel.不幸的是, DataGrid的列定义不继承DataContext ,因为它们不是可视化树的一部分,因此您不能直接绑定到 ViewModel。 You need to resort to a workaround such as the one described in this article :您需要采用一种解决方法,例如本文中描述的方法:

<DataGrid.Resources>
    <local:BindingProxy x:Key="proxy" Data="{Binding}" />
</DataGrid.Resources>

...

<DataGridTextColumn Header="{Binding Data.MyTitle, Source={StaticResource proxy}}"/>

The accepted answer didn't work for me.接受的答案对我不起作用。

I was able to make this work.我能够完成这项工作。

<FrameworkElement x:Name="proxy" DataContext="{Binding}"/>

<DataGridTextColumn Header="{Binding Source={x:Reference proxy}, Path=DataContext.MyTitle}/>

There is no need to use a binding proxy, like too often suggested.没有必要像经常建议的那样使用绑定代理。 Obviously, DataGridColumn.Header is not a DependencyProperty .显然, DataGridColumn.Header不是DependencyProperty To still bind it, simply define the Header explicitly using XAML property element syntax, and bind the header content:要仍然绑定它,只需使用 XAML 属性元素语法明确定义Header ,并绑定 header 内容:

<DataGrid>
  <DataGrid.Columns>
    <DataGridTextColumn>
      <DataGridTextColumn.Header>
        <TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=DataContext.TextValue}" />
      </DataGridTextColumn.Header>
    </DataGridTextColumn>
  </DataGrid.Columns>
</DataGrid>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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