我需要在 DataGridColumnHeader
上使用 Command
对数据进行排序。标准 DataGrid
排序功能对我来说还不够,因为 DataGrid
中并未显示所有数据。我的虚拟机中甚至没有所有数据。 (这是不可能的......太多了)我只是从服务器请求具体的数据页面。现在我还想从排序数据中获取具体页面。
所以我这样做了:
<DataGrid ItemsSource="{Binding Path=Entities, Mode=OneWay}" CanUserSortColumns="False" SelectionMode="Single" SelectedItem="{Binding Path=SelectedEntity}">
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Command" Value="{Binding Path=MyCommand}"/>
<Setter Property="CommandParameter" Value="{Binding Path=Content, RelativeSource={RelativeSource Self}}"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.Columns>
<DataGridTemplateColumn >
<DataGridTemplateColumn.Header>
<DataGridColumnHeader Content="Column1" />
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Property1}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
效果很好。现在我只想拥有 AutoGenerateColumns="True"
不幸的是它不再起作用了。有没有人可以解释为什么它不适用于自动生成的列并为我提供一些解决方案?预先感谢您!
编辑
这可能与以下不起作用有关。
<DataGrid ItemsSource="{Binding Path=Entities, Mode=OneWay}" CanUserSortColumns="False" SelectionMode="Single" SelectedItem="{Binding Path=SelectedEntity}">
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Command" Value="{Binding Path=MyCommand}"/>
<Setter Property="CommandParameter" Value="{Binding Path=Content, RelativeSource={RelativeSource Self}}"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.Columns>
<DataGridTemplateColumn>
<!-- HERE IS THE CHANGE -->
<DataGridTemplateColumn.Header>Column1</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Property1}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
但是应用了样式。我知道这一点是因为我尝试过:
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Background" Value="Tomato"/> <!-- beautiful tomato background -->
<Setter Property="Command" Value="{Binding Path=MyCommand}"/>
<Setter Property="CommandParameter" Value="{Binding Path=Content, RelativeSource={RelativeSource Self}}"/>
</Style>
列标题具有番茄背景,但命令不起作用。
编辑2
解决方法如下。显然 DataGridColumnHeaders
没有继承 DataContext,因为当我更改命令绑定(bind)时,一切都会再次起作用。
<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}},
Path=DataContext.MyCommand}"/>
但是我还是不太明白为什么。所以回答并详细解释将获得赏金。
最佳答案
DataGridColumnHeader是 DataGridColumn.Header 的容器项目例如,与 ListBoxItem 相同是 ListBox 中每个项目的容器项目的ItemsSource 。
由于 ListBoxItem 的 DataContext 将设置为 ListBox 的 ItemsSource 中的项目,因此很自然地将 DataGridColumnHeader 的 DataContext 设置为 DataGridColumn.Header 对象。
关于wpf - 绑定(bind)到 DataGridColumnHeader.Command,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15572666/