0

我在将 XAML 转换为代码隐藏时遇到了麻烦。

我有这个:

<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>

通过DataGrid(伪)填充... new Dataview(ds.Tables[mytable]);

现在我正在尝试在后面的代码中创建样式和触发器,但我遇到了绑定问题。

我有

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);

-唉,它不工作

4

2 回答 2

1

您需要将 Setter 的Property值从

DataGrid.RowBackgroundProperty

DataGridRow.BackgroundProperty

或同等的

Control.BackgroundProperty.
于 2013-10-01T13:55:12.577 回答
0

我建议Style在 XAML 中构建自身,然后在需要时在代码隐藏中获取它。例如,如果一切都发生在 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.. -->

..并在您的代码隐藏中:

var newGrid = new Dataview(ds.Tables[mytable]);
newGrid.RowStyle = this.Resources["MyRowStyle"] as Style;
于 2013-10-01T19:04:44.310 回答