【问题标题】:How to bind column header to property in ViewModel? (WPF MVVM)如何将列标题绑定到 ViewModel 中的属性? (WPF MVVM)
【发布时间】:2013-06-06 15:03:43
【问题描述】:

我的窗口具有绑定到 ViewModel 对象(例如 VM1)的 DataContext。 VM1 有很多属性,其中一个是名为“MyTitle”的字符串。

我在“Window\Grid\DataGrid”中有一个 DataGridTextColumn。如何将 DataGridTextColumn 中的属性“Header”绑定到我的 VM1 ViewModel 中的属性“MyTitle”?

谢谢!

【问题讨论】:

    标签: c# wpf mvvm datagrid datacontext


    【解决方案1】:

    不幸的是,DataGrid 的列定义不继承DataContext,因为它们不是可视化树的一部分,因此您不能直接绑定到 ViewModel。您需要采用一种解决方法,例如 this article 中描述的解决方法:

    <DataGrid.Resources>
        <local:BindingProxy x:Key="proxy" Data="{Binding}" />
    </DataGrid.Resources>
    
    ...
    
    <DataGridTextColumn Header="{Binding Data.MyTitle, Source={StaticResource proxy}}"/>
    

    【讨论】:

    • 给这个人一枚勋章!非常感谢你做的这些!效果很好!
    【解决方案2】:

    接受的答案对我不起作用。

    我能够完成这项工作。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      • 2011-04-13
      • 2015-11-24
      • 2011-02-08
      • 2011-02-01
      相关资源
      最近更新 更多