Ton*_*ile 4 wpf datagrid styles
我的 WPF 应用程序中有DataGrid一个包含对象的控件。该对象有一个布尔属性,可以通过用户操作进行更改。当该属性的值更改时,我需要更改行的样式。
我写了一个继承自以下的类StyleSelector:
public class LiveModeSelector : StyleSelector {
public Style LiveModeStyle { get; set; }
public Style NormalStyle { get; set; }
public override Style SelectStyle( object item, DependencyObject container ) {
DataGridRow gridRow = container as DataGridRow;
LPRCamera camera = item as LPRCamera;
if ( camera != null && camera.IsInLiveMode ) {
return LiveModeStyle;
}
return NormalStyle;
}
}
Run Code Online (Sandbox Code Playgroud)
所讨论的视图模型类实现了INotifyPropertyChanged,并且PropertyChanged当所讨论的属性发生更改时它会引发该事件。
// Note: The ModuleMonitor class implements INotifyPropertyChanged and raises the PropertyChanged
// event in the SetAndNotify generic method.
public class LPRCamera : ModuleMonitor, ICloneable {
. . .
public bool IsInLiveMode {
get { return iIsInLiveMode; }
private set { SetAndNotify( "IsInLiveMode", ref iIsInLiveMode, value ); }
}
private bool iIsInLiveMode;
. . .
/// </summary>
public void StartLiveMode() {
IsInLiveMode = true;
. . .
}
public void StopLiveMode() {
IsInLiveMode = false;
. . .
}
}
Run Code Online (Sandbox Code Playgroud)
当用户执行所需的操作时,属性的值会更改,但样式不会更改。
我在 SelectStyle 方法中放置了一个断点,并且我看到首次加载控件时会命中断点,但当属性值更改时不会命中断点。
我缺少什么?
我找到了一种方法来做到这一点,它源于 @Rachel 对我的问题的回答。然而,代码细节有些不同,我想准确地展示什么是有效的。
第一步是将两个不同的类合并Styles为一个DataGridRow:
<Style TargetType="DataGridRow" x:Key="CameraStyle">
<Setter Property="Foreground" Value="{DynamicResource TextForeground}" />
<Setter Property="Background" Value="{DynamicResource DataBackground}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsInLiveMode}" Value="True">
<Setter Property="Foreground" Value="Red" />
<Setter Property="Background" Value="Yellow" />
</DataTrigger>
</Style.Triggers>
</Style>
Run Code Online (Sandbox Code Playgroud)
第二步是将DataGrid控件的RowStyle属性设置为这个新样式:
<DataGrid . . .
RowStyle={StaticResource CameraStyle}">
. . .
</DataGrid>
Run Code Online (Sandbox Code Playgroud)
这有效。当用户将LPRCamera与该行关联的行置于实时模式时,该行的前景和背景会发生变化,而当用户将其退出实时模式时,该行的前景和背景会变回正常状态,这正是我想要的。
谢谢@雷切尔!
| 归档时间: |
|
| 查看次数: |
5058 次 |
| 最近记录: |