好行为是基于你的招投标工作的精细完美...
你有两个选择......
保持你的代码,因为它是,每当喜好变化请致电DataGrid.Items.Refresh()
或重新绑定DataGrid.ItemsSource
属性以重新生成DataGridRows
。这样,他们将采取改变偏好的效果(即bg和fg颜色会刷新)。
更好的方法是通过Triggers
修补你的逻辑使用基于DynamicResources
Brushes
转色DataGridRows
假设MsgType
的值是有限&在编译时众所周知的......
例如
假设你MsgType
是因此被它代表值的数量方面也定义了一些枚举....
public enum MsgType
{
None = 0,
Read = 1,
Edit = 2,
Delete = 3
}
XAML
<DataGrid.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="MyDefaultPreferences.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</DataGrid.Resources>
...
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter property="BackgroundColor" Value="{DynamicResource NoneMsgTypeBrush}" />
<Style.Triggers>
<DataTrigger Binding="{Binding MsgType}" Value="1">
<Setter Property="BackgroundColor" Value="{DynamicResource ReadMsgTypeBrush}" />
</DataTrigger>
<DataTrigger Binding="{Binding MsgType}" Value="2">
<Setter Property="BackgroundColor" Value="{DynamicResource EditMsgTypeBrush}" />
</DataTrigger>
<DataTrigger Binding="{Binding MsgType}" Value="3">
<Setter Property="BackgroundColor" Value="{DynamicResource DeleteMsgTypeBrush}" />
</DataTrigger>
</Style.Triggers>
</Style>
MyDefaultPreferences.xaml
看起来像下面...
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<SolidColorBrush x:Key="NoneMsgTypeBrush" Color="White"/>
<SolidColorBrush x:Key="ReadMsgTypeBrush" Color="Gray"/>
<SolidColorBrush x:Key="EditMsgTypeBrush" Color="Green"/>
<SolidColorBrush x:Key="DeleteMsgTypeBrush" Color="Red"/> </ResourceDictionary>
所以你必须在运行时做的,当用户改变偏好设置,只需取出后用相同的密钥在MyDefaultPreferences.xaml
添加Brushes
(它的一个Dictionary
)...
例如
如果用户改变阅读消息类型是黄色的,你必须做这个...
Uri uri = new Uri("MyDefaultPreferences.xaml", UriKind.RelativeOrAbsolute);
var _myDefaultResourceDictionary = Application.LoadComponent(uri) as ResourceDictionary;
_myDefaultResourceDictionary.Remove("ReadMsgTypeBrush");
_myDefaultResourceDictionary.Add("ReadMsgTypeBrush", new SolidColorBrush(Colors.Yellow));
这种删除和添加一个刷机资源,改变无论它是通过DynamicResource
称为颜色(即在相应的SolidColorBrush
中)。
这是改变皮肤\在运行时的WPF应用主题的一个非常普遍的方式。
谢谢WPF的话,作为一个快速的解决方案,我已经使用Items.Refresh()解决方案,并能正常工作。我会稍微更改代码以使用DynamicResources,以便正确完成。非常感谢您的快速回复。 –