速记和长写 WPF 绑定等效性

  • 本文关键字:绑定 WPF wpf xaml
  • 更新时间 :
  • 英文 :


我正在尝试使一些 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>

最新更新