我正在尝试使一些 XAML 片段更具可读性(不是生产代码,只是为了让我更好地了解 XAML 内部工作原理)。原始代码是
<CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}}">
我已将其更改为
<CheckBox>
<CheckBox.IsChecked>
<Binding Path="IsSelected" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">
<Binding.Source>
<RelativeSource Mode="FindAncestor" AncestorType="{x:Type DataGridRow}"/>
</Binding.Source>
</Binding>
</CheckBox.IsChecked>
</CheckBox>
第一个窗体工作正常(它正确地将复选框的 IsChecked 属性绑定到容器的 IsSelected 属性(DataGridRow)。第二个不起作用。它应该如何正常工作?
这是因为您在第二种情况下设置了<Binding.Source>
而不是<Binding.RelativeSource>
。如果您设置<Binding.RelativeSource>
它也可以工作。
<CheckBox>
<CheckBox.IsChecked>
<Binding Path="IsSelected" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">
<Binding.RelativeSource>
<RelativeSource Mode="FindAncestor" AncestorType="{x:Type DataGridRow}"/>
</Binding.RelativeSource>
</Binding>
</CheckBox.IsChecked>
</CheckBox>