[英]Changing specific wpf datagrid row color using c#
我需要在运行时更改特定数据网格行的颜色
我在数据网格的加载行事件中设置行背景色
private void MessagesDataGrid_LoadingRow(objects , DataGridRowEventArgs e)
{
var v = e.Row.Item.ToString();
int i = e.Row.GetIndex();
if (IoStatusViewModel.HighlightSelected == true )
{
e.Row.Focusable = true;
e.Row.Background = Brushes.Red;
if (v.Contains("MCP :"))
{
DisplayLogs = IoStatusViewModel.ChangeMcpLog(v);
e.Row.Item = DisplayLogs;
}
}
else
{
if (v.Contains("MCP :"))
{
DisplayLogs = IoStatusViewModel.ChangeMcpLog(v);
e.Row.Item = DisplayLogs;
}
}
}
这段代码在数据网格加载时运行良好,但是一段时间后,数据网格中每行的颜色开始改变,随着时间的流逝,整个网格变成红色
我将在您要绑定的类对象以及网格样式中执行此操作。 首先,您的数据将显示在网格中。 这是怎么来的/从哪里来的。 是某种List <>或ObservableCollect <>项。 例
var yourBoundProperty = new List<SomeClass>();
…随便填充。
public class SomeClass
{
public string SomeProp {get; set;}
public string YourMCPField {get; set;}
// make a SPECIAL FIELD... could be boolean, number setting, whatever flag
// but in this case, I just have boolean
public bool FieldContainsMCP { get { return YourMCPFieldContains( "MCP :"); }}
}
现在,在您的Xaml中...假设在Window声明中。
<Window … >
<Window.Resources>
<Style TargetType="{x:Type DataGridCell}" x:Key="MyColorTriggers">
<Style.Triggers>
<DataTrigger Binding="{Binding FieldContainsMCP}" Value="True">
<Setter Property="Background" Value="Red" />
<Setter Property="ExampleAnyOtherProperty" Value="someOtherValue" />
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<DataGrid … other settings you have
CellStyle="{StaticResource MyColorTriggers}" >
.. rest of your data column declarations
</DataGrid>
</Window>
这样,实际数据源便是标记基础,无论您在何处滚动记录,都将其应用于CellStyle触发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.