所以,例如我有一些简单模型的MVVM WPF应用程序:
public class MyObject
{
public string F1 { get; set; }
public string F2 { get; set; }
}
和创建3行的简单视图模型:
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"}
};
}
}
在视图中,我有DataGrid
手动定义的列,每列都设置CellStyle
。这两种样式都在Window.Resources
块中定义。但是对于第一列,我使用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>
所以问题是:在第二列中,资源没有应用于列。
答案 0 :(得分:1)
您可以在DataGridCell
Style
中为属性创建资源,然后在DynamicResource
定义中将其作为Style
引用:
根据您的示例,它看起来像这样:
<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>
资源当然会位于不同的资源文件中。
答案 1 :(得分:0)
我使用一点服务找到了解决方案。用几句话我用xaml写这段代码:
<wpfApplication12:DataGridColumnDynamicStyleService TargetGrid="{Binding ElementName=Grid}">
<wpfApplication12:DataGridColumnDynamicStyleService.ColumnStyles>
<wpfApplication12:DataGridColumnStyleBinding ColumnTag="C1" DynamicStyle="{DynamicResource BaseCellClass}" />
</wpfApplication12:DataGridColumnDynamicStyleService.ColumnStyles>
</wpfApplication12:DataGridColumnDynamicStyleService>
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding ElementName=WholeWindow, Path=ViewModel.Objects}" x:Name="Grid">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding F1}" Header="F1" wpfApplication12:DataGridColumnDynamicStyle.ColumnTag="C1" />
<DataGridTextColumn Binding="{Binding F2}" Header="F2" wpfApplication12:DataGridColumnDynamicStyle.ColumnTag="C2" />
</DataGrid.Columns>
</DataGrid>
在这里,正如您所看到的,我使用附加属性ColumnTag来标识列。我创建了一个服务控件,用于定义列的样式并将目标数据网格设置为TargetGrid
如果您想查看所有代码,请参阅google drive