[英]Change DataGrid Column Headers in WPF
我有一個 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 Viewmodel 和我想將標題綁定到這樣的屬性:
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?
如果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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.