我有一个带有自定义头的WPF DataGrid。DataGrid绑定到视图模型中的CollectionViewSource
属性。datagrid列是在codebheath中创建的。
当我更改集合时,datagrid会更新并显示新数据。但是,自定义头不会更新-它仍然绑定到应该已经超出范围的旧对象。换句话说,报头仅在第一次被绑定。之后,即使ItemsSource发生了变化,它也会保留旧对象。
如何修复它,以便在数据更改时,头文件与数据网格的其余部分同时更新?
<DataGrid
AutoGenerateColumns="False"
CanUserAddRows="False"
CanUserDeleteRows="False"
CanUserReorderColumns="False"
CanUserResizeRows="False"
CanUserSortColumns="True"
IsReadOnly="True"
ItemsSource="{Binding Path=PreformDataListViewSource.View}">
</DataGrid>
<!-- Custom header -->
<Style TargetType="{x:Type DataGridColumnHeadersPresenter}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridColumnHeadersPresenter}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="30"></RowDefinition>
</Grid.RowDefinitions>
<!-- HEADER 1: Extra header row. For some reason, it does not re-bind when there are
changes to the data.
The ToggleButton will keep showing the status of an old out-of-scope object. -->
<StackPanel Orientation="Horizontal"
Grid.Row="0" >
<ItemsControl
ItemsSource="{TemplateBinding ItemsSource, diag:PresentationTraceSources.TraceLevel=High}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ToggleButton x:Name="btPlotHeader"
IsChecked="{Binding IsSelectedForPlotting, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged }"
Command="{Binding CommandPlotColumn}">
</ToggleButton>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
<!-- HEADER 2: These 2 controls are the default header with sortable headings. -->
<DataGridColumnHeader
x:Name="PART_FillerColumnHeader"
Grid.Row="1"
IsHitTestVisible="False" />
<ItemsPresenter Grid.Row="3" />
视图模型:
public class MyVM: BindableBase
{
private ObservableCollection<PreformDataVM> preformDataList;
public MyVM()
{
this.PreformDataList = new ObservableCollection<PreformDataVM>();
this.PreformDataListViewSource = new CollectionViewSource()
{
Source = this.PreformDataList,
};
}
/// <summary>
/// Gets the CollectionViewSource. The purpose of this collection is to preserve
sorting when the data is reloaded / refreshed.
/// </summary>
public CollectionViewSource PreformDataListViewSource
{
get; private set;
}
public ObservableCollection<PreformDataVM> PreformDataList
{
get
{
return this.preformDataList;
}
set
{
this.SetProperty(ref this.preformDataList, value);
}
}
}
1条答案
按热度按时间vkc1a9a21#
我做了一个变通方案,即在每次数据更改时重新创建DataGrid列。
以前,我只在开始时和数据格式更改时创建列。
现在列标题总是显示正确的数据。