设置动态datagridtextcolumn标题
我正在尝试为我的datagrid设置动态标头样式。
我可以为整个DataGrid设置Columnheader样式,但是为单列设置样式不起作用。该样式不应用于列。
mainwindow.xaml
<Window x:Class="StyleTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<CheckBox Content="Themes" IsChecked="False" Unchecked="CheckBox_Unchecked" Checked="CheckBox_Checked" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="60,92,0,0"/>
<DataGrid d:ItemsSource="{d:SampleData ItemCount=5}" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,150,0,0" AutoGenerateColumns="False"
ColumnHeaderStyle="{DynamicResource ColumnHeaderTest}">
<DataGrid.Columns>
<DataGridTextColumn Header="SampleInt" Binding="{Binding SampleInt}"/>
<DataGridTextColumn Header="SampleStringA" Binding="{Binding SampleStringA}"/>
<DataGridTextColumn Header="SampleStringB" Binding="{Binding SampleStringB}" HeaderStyle="{DynamicResource ColumnHeaderTest}"/>
<DataGridCheckBoxColumn Header="SampleBool" Binding="{Binding SampleBool, Mode=OneWay}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
mainwindow.xaml.cs
using System;
using System.Linq;
using System.Windows;
namespace StyleTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
foreach (var dictionary in App.Current.Resources.MergedDictionaries.ToList())
{
App.Current.Resources.MergedDictionaries.Remove(dictionary);
}
}
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
foreach (var dictionary in App.Current.Resources.MergedDictionaries.ToList())
{
App.Current.Resources.MergedDictionaries.Remove(dictionary);
}
App.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("pack://application:,,,/Themes/Theme1.xaml") });
}
}
}
/theme/them1.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="{x:Type DataGridColumnHeader}" x:Key="ColumnHeaderTest">
<Setter Property="Background" Value="Green"/>
</Style>
</ResourceDictionary>
app.xaml和app.xaml.cs均为默认情况下,没有添加代码。
结果
这是一个完整的示例项目,证明了问题。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我唯一能够提出的解决方案是,每当主题更改时,都要在代码中手动更改标题样式。
The only solution I was able to come up with was to manually change the header style in code whenever the theme changes.