XAML代码落后

时间:2013-10-01 13:28:37

标签: wpf xaml styles code-behind datatrigger

我在将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);

- 它无法正常工作

2 个答案:

答案 0 :(得分:1)

您需要更改来自

的Setter的Property
DataGrid.RowBackgroundProperty

DataGridRow.BackgroundProperty

或等效的

Control.BackgroundProperty.

答案 1 :(得分:0)

我建议在XAML中构建Style本身,然后在需要时在代码隐藏中获取它。例如,如果所有内容都发生在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;