Reputation: 523
I am pretty new to binding, and WPF in general.
Now I have created a DataGrid in my XAML view. I then created two DataGridTextColumns
DataGridTextColumn col1 = new DataGridTextColumn();
col1.Binding = new Binding("barcode");
I then add a the columns to the dataGrid. When I want to add a new item to the datagrid, I can just do,
dataGrid1.Items.Add(new MyData() { barcode = "barcode", name = "name" });
This is great and works fine (I know there are lots of ways to do this, but this is the most simple for me now).
However, the problem hits when I try to do the next thing;
I want to add these items to the dataGrid, but with different foreground colours depending on certain conditions. I.e -
if (aCondition)
dataGrid.forgroundColour = blue;
dataGrid.Items.Add(item);
Upvotes: 0
Views: 341
Reputation: 184516
Use Triggers for example:
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<DataTrigger Binding="{Binding ACondition}" Value="True">
<Setter Property="TextElement.Foreground" Value="Blue" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
For this to work your items of course need to have a property called ACondition
.
Edit: An example (assumes that you might want to change the property at runtime and thus implements INotifyPropertyChanged
)
public class MyData : INotifyPropertyChanged
{
private bool _ACondition = false;
public bool ACondition
{
get { return _ACondition; }
set
{
if (_ACondition != value)
{
_ACondition = value;
OnPropertyChanged("ACondition");
}
}
}
//...
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Upvotes: 3