Reputation: 5008
I'm having troubles with converting XAML to codebehind.
I have this:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding state}" Value="True">
<Setter Property="Background" Value="GreenYellow"/>
</DataTrigger>
<DataTrigger Binding="{Binding state}" Value="False">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
the DataGrid
is populated via the (pseudo) ... new Dataview(ds.Tables[mytable]);
now I'm trying to create the style and trigger in the code behind but I'm having trouble with the Binding.
I have
BrushConverter brushConverter = new BrushConverter();
Style setcolor = new Style();
setcolor.TargetType = typeof(DataGridRow);
DataTrigger setgreen = new DataTrigger();
setgreen.Binding = new Binding("state");
setgreen.Value = true;
setgreen.Setters.Add(new Setter(DataGrid.RowBackgroundProperty, brushConverter.ConvertFromString(Colors.GreenYellow.ToString())));
setcolor.Triggers.Add(setgreen);
-Alas it is not working
Upvotes: 0
Views: 1195
Reputation: 13017
I would recommend building the Style
itself in XAML, and then fetch it in your code-behind whenever you need it. For example, if everything happens in a UserControl
:
<UserControl x:Class=...
...
>
<UserControl.Resources>
<Style x:Key="MyRowStyle" TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding state}" Value="True">
<Setter Property="Background" Value="GreenYellow"/>
</DataTrigger>
<DataTrigger Binding="{Binding state}" Value="False">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
<!-- Your content here.. -->
..and in your code-behind:
var newGrid = new Dataview(ds.Tables[mytable]);
newGrid.RowStyle = this.Resources["MyRowStyle"] as Style;
Upvotes: 0
Reputation: 128013
You need to change the Setter's Property
value from
DataGrid.RowBackgroundProperty
to
DataGridRow.BackgroundProperty
or the equivalent
Control.BackgroundProperty.
Upvotes: 1