How do I programatically change datagrid row color in WPF?
I was wondering if this possible. I have this datagrid contains 3 columns and 2 rows. What I want is to change the background of the URL column on my datagrid according to the data I enter.
Here is sample of my xaml code:
<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>
My class used to fill up the datagrid with rows:
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; }
}
And here is my way to add rows to the control:
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);
I have two elements. Each row should have its o开发者_开发技巧wn color. The first one should be red and the second one should be blue. I really don't know how to make the control use the rowColor value.
What do I need to do to get this working?
Your rowColor
should not return a string (i would rename it to RowColor
since it is public), just return the actual colour-brushes instead. (Your colours are wrong by the way, the first is opaque black and the second is transparent blue)
e.g.
public Brush rowColor { get; set; }
data1.rowColor = Brushes.Red;
data2.rowColor = Brushes.Blue;
If you really need to parse from string you could use a value converter or the standard conversion that is used when parsing Xaml.
Besides that i am not sure if binding those properties to Foreground
of the column will work.
精彩评论