[英]How to change Datagrid row color at runtime in wpf?
我正在使用WPF DataGrid並在運行時通過使用類RowItem添加行
public class RowItem //Class
{
public int Rule_ID { get; set; }
public string Rule_Desc { get; set; }
public Int64 Count_Of_Failure { get; set; }
}
adding row at run time like :
dgValidateRules.Items.Add(new RowItem() { Rule_ID = ruleID, Rule_Desc = ruleDesc, Count_Of_Failure = ttlHodlings });
使用下面的“加載行”事件代碼來更改數據網格行的顏色。 但是它不起作用。
private void dgValidateRules_LoadingRow(object sender, DataGridRowEventArgs e)
{
for (int i = 1; i < dgValidateRules.Items.Count; i++)
{
if (((RowItem)dgValidateRules.Items[i]).Count_Of_Failure == 0)
e.Row.Foreground = new SolidColorBrush(Colors.Black);
else
e.Row.Foreground = new SolidColorBrush(Colors.Red);
}
}
有人可以告訴我解決方案嗎?
因為它是行事件,所以在這里很累,因此您可以在該行上放置一個條件:
private void table_LoadingRow(object sender, DataGridRowEventArgs e)
{
if (((MyData)e.Row.DataContext).Module.Trim().Equals("SomeText"))
{
e.Row.Foreground = new SolidColorBrush(Colors.Red);
}
}
您可以使用DataTrigger或Converter
<DataGrid ItemsSource="{Binding YourItemsSource}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding Count_Of_Failure}" Value="0">
<Setter Property="Foreground" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding Count_Of_Failure}" Value="1">
<Setter Property="Foreground" Value="Green"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.