簡體   English   中英

如何在WPF中以編程方式更改datagrid行的顏色?

[英]How do I programatically change datagrid row color in WPF?

我想知道這是否可能。 我有這個datagrid包含3列和2行。 我要根據輸入的數據更改datagrid上URL列的背景。

這是我的xaml代碼的示例:

<DataGrid
    x:Name="mylistview"
    BorderBrush="#FF373737"
    Background="Black"
    VerticalGridLinesBrush="#FF232323"
    HorizontalGridLinesBrush="#FF212121">
    <DataGrid.Columns>
        <DataGridTextColumn Header="URL" Foreground="{Binding rowColor}" Binding="{Binding url}"/>
        <DataGridTextColumn Header="Version" Foreground="White" Binding="{Binding version}"/>
        <DataGridTextColumn Header="Valid" Foreground="White" Binding="{Binding valid}"/>
    </DataGrid.Columns>
</DataGrid>

我的班級曾經用行填充數據網格:

public class myData
{
    public string url {get; set;}
    public string version{get; set;}
    public string valid{get; set;}

    //this should be the value that changes the bg color 
    public string rowColor{ get; set; }
}

這是我向控件添加行的方法:

 myData data1 = new myData();
 data1.url = "http://google.com";
 data1.valid = "yes";
 data1.version = "1";
 data1.rowColor = "#FF000000";
 this.mylistview.Items.Add(data1);

 data1.url = "http://yahoo.com";
 data1.valid = "no";
 data1.version = "1";
 data1.rowColor = "#000000FF";
 this.mylistview.Items.Add(data1);

我有兩個要素。 每行應具有自己的顏色。 第一個應該是紅色,第二個應該是藍色。 我真的不知道如何使控件使用rowColor值。

我需要做什么才能使它正常工作?

您的rowColor不應返回字符串(我將其重命名為RowColor因為它是公共的),而只是返回實際的顏色畫筆。 (順便說一句,您的顏色是錯誤的,第一個是不透明的黑色,第二個是透明的藍色)

例如

public Brush rowColor { get; set; }
data1.rowColor = Brushes.Red;
data2.rowColor = Brushes.Blue;

如果您確實需要從字符串中進行解析,則可以使用值轉換器或解析Xaml時使用的標准轉換。

除此之外,我不確定將這些屬性綁定到列的Foreground是否可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM