Reputation: 2708
I have a DataGrid in WPF and I want to bind the BackgrounColor of the rows to a property to individual items in the collection that I am providing as the ItemsSource to the datagrid.
public class Log: INotifyPropertyChanged
{
private string _timestamp;
private string _threadName;
private string _userName;
private string _message;
private Brush _backgroundColor;
public string Timestamp
{
get { return _timestamp; }
set
{
if (_timestamp == value) return;
_timestamp = value;
NotifyPropertyChanged("Timestamp");
}
}
public string ThreadName
{
get { return _threadName; }
set
{
if (_threadName == value) return;
_threadName = value;
NotifyPropertyChanged("ThreadName");
}
}
public string UserName
{
get { return _userName; }
set
{
if (_userName == value) return;
_userName = value;
NotifyPropertyChanged("UserName");
}
}
public string Message
{
get { return _message; }
set
{
if (_message == value) return;
_message = value;
NotifyPropertyChanged("Message");
}
}
public string BackgroundColor
{
get { return _backgroundColor; }
set
{
if (_backgroundColor== value) return;
_backgroundColor = value;
NotifyPropertyChanged("BackgroundColor");
}
}
public bool IsCustomLog = false;
public string HighlightColor = null;
public event PropertyChangedEventHandler PropertyChanged;
//Constructor
public Log(string timestamp, string threadName, string userName, string message, Brush backgroundColor)
{
UserName = userName;
Timestamp = timestamp;
ThreadName = threadName;
Message = message;
BackgroundColor = backgroundColor;
}
//Methods
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
And I am trying to bind the BackgroundColor of the datagrid row to the BackgroundColor property in the Log class.
I try to bind it like this:
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="FontSize" Value="14"/>
<Setter Property="FontFamily" Value="Arial"/>
<Setter Property="BorderThickness" Value="0,0,2,2"/>
<Setter Property="Background" Value="{Binding BackgroundColor}"/>
<Setter Property="BorderBrush" Value="#CCCCCC"/>
</Style>
</DataGrid.RowStyle>
But it does not set the background color. I do not know what I am doing wrong.
Upvotes: 0
Views: 941
Reputation: 73
I'm not sure if it is a typo in your code since _backgroundColor
is Brush
while BackgroundColor
is string
:
public string BackgroundColor
{
get { return _backgroundColor; }
set
{
if (_backgroundColor== value) return;
_backgroundColor = value;
NotifyPropertyChanged("BackgroundColor");
}
}
I suggest you to make the BackgroundColor
a Color
since the 'Color' postfix of your property name, and change the 'Setter' in XAML like this:
<Setter Property="Background">
<SolidColorBrush Color="{Binding BackgroundColor}"/>
</Setter>
Upvotes: 1