我在将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);
- 它无法正常工作
答案 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;