在WPF

2017-10-09 70 views
-1

更改數據網格列標題我有一個數據網格如下所示在WPF

<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? 

回答

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> 
+0

我會記住這爲答案,但我怎麼能實現屬性更改。我想在運行時更改列? – KMarto

+0

這應該只是將Header1源屬性設置爲新值並引發PropertyChanged事件的問題。但如果您有其他問題,請提出一個新問題。 – mm8