gpt4 book ai didi

c# - 行的WPF DataGrid StyleSelector

转载 作者:行者123 更新时间:2023-12-03 10:52:44 25 4
gpt4 key购买 nike

我正在尝试使用ItemContainerStyleSelector根据定义行的对象的类型在数据网格中显示不同的行样式(ItemsSource是IGridItem的集合,有GridItemGridSeparator应该具有不同的样式)。我的问题是,从未调用过我的StyleSelector的SelectStyle。现在,我发现(here)问题可能是继承的样式(MahApps Metro库重新定义了所有标准控件的默认样式),这可能已经设置了ItemContainerStyle。

所以现在我的问题是:是否有办法仍然使用我的StyleSelector,以便将继承的样式作为所选样式的基础?如果不是,如何根据对象类型为某些行实现不同的样式?

编辑:
手动将ItemContainerStyle设置为null无效,仍然不会调用我的StyleSelector的SelectStyle

编辑2:
由于我没有像Grx70那样得到System.Windows.Data Error: 24 : Both 'ItemContainerStyle' and 'ItemContainerStyleSelector' are set; 'ItemContainerStyleSelector' will be ignored.,因此我认为ItemContainerStyle不是问题,就像我最初想的那样。

jstreet指出,它与MahApps.Metro有关,但是...(请参阅他的评论)

我当前的实现:

<DataGrid ItemsSource="{Binding Items}" ItemContainerStyleSelector="{StaticResource StyleSelector}">

Syle选择器:
public class GridRowStyleSelector : StyleSelector
{
private readonly ResourceDictionary _dictionary;

public GridRowStyleSelector()
{
_dictionary = new ResourceDictionary
{
Source = new Uri(@"pack://application:,,,/myApp;component/View/GridResources.xaml")
};
}

public override Style SelectStyle(object item, DependencyObject container)
{
string name = item?.GetType().Name;
if (name != null && _dictionary.Contains(name))
{
return (Style)_dictionary[name];
}
return null;
}
}

GridResources.xaml具有测试值:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="GridItem" TargetType="DataGridRow">
<Setter Property="BorderThickness" Value="3"/>
</Style>
<Style x:Key="GridSeparator" TargetType="DataGridRow">
<Setter Property="BorderBrush" Value="Red"/>
</Style>
</ResourceDictionary>

最佳答案

我想我找到了罪魁祸首。事实证明,处理DataGrid中的行样式的正确方法是通过RowStyleRowStyleSelector属性,而不是ItemContainerStyleItemContainerStyleSelector。它们有效,但仅在您显式使用RowStyleRowStyleSelector之前有效。这正是MahApps Metro所做的-它设置RowStyle值(我相信通过覆盖DataGrid默认样式)。然后我认为ItemContainerStyle是由DataGrid在内部设置的(一些测试表明,尽管ItemContainerStyle明确设置为null,但仍已设置)。

综上所述,这应该为您解决问题:

<DataGrid ItemsSource="{Binding Items}"
RowStyle="{x:Null}"
RowStyleSelector="{StaticResource StyleSelector}">
(...)
</DataGrid>

同样,要修改MahApps行样式而不是完全放弃它,您应该基于MahApps行样式:
<Style x:Key="GridItem" TargetType="DataGridRow"
BasedOn="{StaticResource MetroDataGridRow}">
<Setter Property="BorderThickness" Value="3"/>
</Style>
<Style x:Key="GridSeparator" TargetType="DataGridRow"
BasedOn="{StaticResource MetroDataGridRow}">
<Setter Property="BorderBrush" Value="Red"/>
</Style>

关于c# - 行的WPF DataGrid StyleSelector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36881121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com