【问题标题】:WPF Bind to a different property path when binding value is null当绑定值为空时,WPF 绑定到不同的属性路径
【发布时间】:2012-11-26 14:01:04
【问题描述】:

我需要做一些类似于 PriorityBinding 的事情,除了在绑定为 null 时使用较低优先级的绑定(而不是在绑定无效时,如在 PriorityBinding 中)。我似乎无法找到一种“好”的方法来做到这一点,除非创建两个重复的控件,每个控件都有我想要使用的每个绑定,并根据绑定是否为空来触发它们的可见性。必须有更好的方法,因为我不想每次需要更改某些内容时都更新两个控件(重复代码 == 不好)。

例子:

当 SelectedItem.SelectedItem 不为空时:

<ContentControl Content="{Binding SelectedItem.SelectedItem}"/>

当 SelectedItem.SelectedItem 为空时:

<ContentControl Content="{Binding SelectedItem}"/>

使用这样的样式不起作用:

<ContentControl Content="{Binding SelectedItem.SelectedItem}">
    <ContentControl.Style>
        <Style TargetType="ContentControl">
            <Style.Triggers>
                <DataTrigger Binding="{Binding SelectedItem.SelectedItem}" Value="{x:Null}">
                    <Setter Property="Content" Value="{Binding SelectedItem}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ContentControl.Style>
</ContentControl>

我猜这不起作用,因为样式中的绑定正在尝试使用 ContentControl 的 Content 属性作为它们的源,因此 DataTrigger 正在实际测试SelectedItem.SelectedItem.SelectedItem.SelectedItem。有什么想法吗?

【问题讨论】:

  • 您可以使用转换器并像 Content="{Binding SelectedItem,...}" 进行绑定。在转换器中检查 SelectedItem.SelectedItem - 属性:如果 null 返回 SelectedItem,否则返回 SelectedItem.SelectedItem
  • 如果您在转换器中这样做,我认为它不会捕获属性更改,绑定如何知道 SelectedItem.SelectedItem 已更改?
  • 好主意,应该可以,谢谢!

标签: wpf xaml data-binding


【解决方案1】:

您可以使用 MultiBinding 来实现您想要的:

<ContentControl Content="{Binding SelectedItem.SelectedItem}">
    <ContentControl.Content>
        <MultiBinding Converter="{StaticResource ResourceKey=myConverter}">
            <Binding Path="SelectedItem"/>
            <Binding Path="SelectedItem.SelectedItem"/>
        </MultiBinding>
    </ContentControl.Content>
</ContentControl>

您的转换器可能看起来像

public class MyMultiConverter:IMultiValueConverter
{
   public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
   {
      if (values[1] == null)
          return values[0];

      return values[1];
   }

   public object[] ConvertBack(object values, Type[] targetType, object parameter, CultureInfo culture)
   {
      return null;
   }
}

【讨论】:

    猜你喜欢
    • 2019-12-12
    • 2010-11-01
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 2015-08-30
    • 2017-09-14
    相关资源
    最近更新 更多