WPF绑定值为null时绑定到不同的属性路径

时间:2012-11-26 14:01:04

标签: wpf xaml data-binding

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

示例:

当SelectedItem.SelectedItem不为null时:

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

当SelectedItem.SelectedItem为null时:

<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。有什么想法吗?

1 个答案:

答案 0 :(得分:4)

您可以使用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;
   }
}
相关问题