2012-08-23 158 views
0

我使用WPF DataGrid和使用類RowItem如何在運行時更改wpf中的Datagrid行顏色?

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 }); 

用於改變DataGrid行的顏色下面的加載行事件代碼添加在運行時行。但它不工作。

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); 
    } 
} 

有人可以告訴我解決方案嗎?

+0

Wooow做只要看看你的問題....你是否期望任何人都會費心去閱讀那個爛攤子?發佈前請格式化您的問題。 – Reniuz

+0

你想要改變什麼?該行的背景顏色或前景色。請注意,前景色將改變文字顏色。 – Bathineni

+0

是的,我需要改變文本顏色。 – janakiakula

回答

0

因爲它排事件有它是撥錯地方做它,在這裏你可以放置一個條件有關行:

private void table_LoadingRow(object sender, DataGridRowEventArgs e) 
    { 
     if (((MyData)e.Row.DataContext).Module.Trim().Equals("SomeText")) 
     { 
      e.Row.Foreground = new SolidColorBrush(Colors.Red); 
     } 
    } 
0

您可以用DataTriggerConverter

<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> 
相關問題