![](/img/trans.png)
[英]C# WPF: Use RadioButton IsChecked property for DataTrigger
[英]WPF:Using checkbox IsChecked property in DataTrigger
我試圖在DataTrigger中使用WPF復選框的IsChecked屬性。基於我設置特定DataGridRow背景的值。
我的工作代碼
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Background" Value="LightGray" />
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=chkbox, Path=IsChecked}" Value="true">
<Setter Property="Background" Value="LightCyan" />
</DataTrigger>
</Style.Triggers>
</Style>
<DataGrid x:Name="dataGrid1" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn MinWidth="40" Width="Auto" Header="Select">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox x:Name="chkbox" IsChecked="{Binding Selected, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"></CheckBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
然后我檢查了這個鏈接並更改了下面的代碼,它工作正常.Here Selected是我的公共財產。
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Background" Value="LightGray" />
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Selected}" Value="true">
<Setter Property="Background" Value="LightCyan" />
</DataTrigger>
</Style.Triggers>
</Style>
請幫我理解為什么我的原始代碼不起作用? 我錯過了什么。
谷歌沒有幫助。令人驚訝的是,SO上也沒有線索! 感謝您的幫助。
原始代碼無法正常工作,因為您嘗試通過ElementName
定位對象,該對象作為模板化對象存在,因此在綁定嘗試解析之后才會創建。 通常,您只應在引用可視樹中的祖先對象時使用ElementName
,而不應使用子項,尤其是模板化子項。
正如評論中所提到的,也不可能在這里使用{RelativeSource FindAncestor...
綁定,因為CheckBox
是DataGridRow
的子{RelativeSource FindAncestor...
,而不是祖先。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.