【问题标题】:Change DataGrid Column Headers in WPF在 WPF 中更改 DataGrid 列标题
【发布时间】:2018-03-20 14:42:17
【问题描述】:

我有一个如下所示的 DataGrid

    <DataGrid x:Name="dataGrid" Margin="0,5,10,5" AutoGenerateColumns="False" ItemsSource="{Binding Products, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  >
    <DataGrid.Columns>
      <DataGridTextColumn x:Name="productName" Binding="{Binding Path Name}" Header="Name To Change">
    </DataGrid.Columns>

对于我正在使用 DataContextSpy 的代码

    public class DataContextSpy : Freezable
{
    public DataContextSpy()
    {
        // This binding allows the spy to inherit a DataContext.
        BindingOperations.SetBinding(this, DataContextProperty, new Binding());
    }

    public object DataContext
    {
        get { return GetValue(DataContextProperty); }
        set { SetValue(DataContextProperty, value); }
    }

    // Borrow the DataContext dependency property from FrameworkElement.
    public static readonly DependencyProperty DataContextProperty = FrameworkElement
        .DataContextProperty.AddOwner(typeof(DataContextSpy));

    protected override Freezable CreateInstanceCore()
    {
        // We are required to override this abstract method.
        throw new NotImplementedException();
    }
}

然后我有 MVVM 视图模型,我想将标题绑定到这样的属性:

    public class ViewModel: ViewModelBase{
    string header1;
    Public string Header1{
    get{return header1;}
    set{
    Set(ref header1, value);
    }
    ...........
    My question is why is it not binding to the property? Anny suggestions?

【问题讨论】:

    标签: c# wpf mvvm mvvm-light


    【解决方案1】:

    如果Header1 定义在与Products 属性相同的视图模型类中,您可以像这样使用HeaderTemplate

    <DataGridTextColumn x:Name="productName" Binding="{Binding Path=Name}">
        <DataGridTextColumn.HeaderTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=DataContext.Header1, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
            </DataTemplate>
        </DataGridTextColumn.HeaderTemplate>
    </DataGridTextColumn>
    

    【讨论】:

    • 我会将此标记为答案,但如何实现属性更改。我想在运行时更改列?
    • 这应该只是将 Header1 源属性设置为新值并引发 PropertyChanged 事件的问题。但是,如果您有其他问题,请提出一个新问题。
    猜你喜欢
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 2011-09-20
    相关资源
    最近更新 更多