gpt4 book ai didi

c# - 为什么我不能将 DynamicResource 与 DataGridColumn.CellStyle 一起使用

转载 作者:太空狗 更新时间:2023-10-29 23:46:26 27 4
gpt4 key购买 nike

例如,我有一些具有简单模型的 MVVM WPF 应用程序:

public class MyObject
{
public string F1 { get; set; }
public string F2 { get; set; }
}

和创建 3 行的简单 View 模型:

public class MyViewModel
{
public ObservableCollection<MyObject> Objects { get; set; }

public MyViewModel()
{
Objects = new ObservableCollection<MyObject>
{
new MyObject{F1 = "V1",F2 = "B1"},
new MyObject{F1 = "V2",F2 = "B2"},
new MyObject{F1 = "V3",F2 = "V3"}
};
}
}

在 View 中,我有一个包含手动定义列的 DataGrid,并且我为每一列设置了 CellStyle。两种样式都在 Window.Resources block 中定义。但是对于第一列,我使用 StaticResource,对于第二列,我使用 DynamicResource

查看 XAML:

<Window x:Class="WpfApplication12.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" x:Name="WholeWindow">
<Window.Resources>
<Style x:Key="BaseCellClass" TargetType="DataGridCell">
<Setter Property="Foreground" Value="Blue" />
</Style>
</Window.Resources>
<Grid>
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding ElementName=WholeWindow, Path=ViewModel.Objects}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding F1}" Header="F1" CellStyle="{StaticResource BaseCellClass}" />
<DataGridTextColumn Binding="{Binding F2}" Header="F2" CellStyle="{DynamicResource BaseCellClass}" />
</DataGrid.Columns>
</DataGrid>
</Grid>

所以问题是:在第二列中,资源没有应用到该列。

see second column

最佳答案

您可以为 DataGridCell 中的属性创建资源Style然后将它们引用为 DynamicResourceStyle 内定义:

根据您的示例,它看起来像这样:

<Window.Resources>
<SolidColorBrush x:Key="ForegroundBrush" Color="Blue"/>

<Style x:Key="BaseCellClass" TargetType="DataGridCell">
<Setter Property="Foreground" Value="{DynamicResource ForegroundBrush}" />
</Style>
</Window.Resources>
<Grid>
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding ElementName=WholeWindow, Path=ViewModel.Objects}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding F1}" Header="F1" CellStyle="{StaticResource BaseCellClass}" />
<DataGridTextColumn Binding="{Binding F2}" Header="F2" CellStyle="{StaticResource BaseCellClass}" />
</DataGrid.Columns>
</DataGrid>
</Grid>

资源当然会位于单独的资源文件中。

关于c# - 为什么我不能将 DynamicResource 与 DataGridColumn.CellStyle 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17475083/

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