Search code examples
wpfxamlstylescode-behinddatatrigger

XAML to codebehind


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


Solution

  • You need to change the Setter's Property value from

    DataGrid.RowBackgroundProperty
    

    to

    DataGridRow.BackgroundProperty
    

    or the equivalent

    Control.BackgroundProperty.