将3个可见性绑定到一个

时间:2015-01-07 11:08:38

标签: wpf visibility

我正在研究WPF mvvm项目。我设计了一个包含3个标签的堆栈面板。每个标签都有其可见性。我想隐藏所有3个标签时隐藏面板的可见性。

        <StackPanel Visibility="{Binding cond1 || cond2 || cond3}"  >
          <Label Visibility="{Binding cond1}" Content="1"/>
          <Label Visibility="{Binding cond2}" Content="2"/>
          <Label Visibility="{Binding cond3}" Content="3"/>
        </StackPanel>

我该怎么做。 感谢

3 个答案:

答案 0 :(得分:1)

其中一个选项是使用MultiValueConverters:

http://www.codeproject.com/Articles/328978/Introduction-to-multi-binding-and-multi-value-conv

另一个选项是在您的viewmodel中公开 MergedCondition

public bool MergedCondition 
{
  get
  {
     return cond1 || cond2 || cond3;
  }
}

如果任何条件发生变化,您还需要提出MergedCondition已更改:

public bool cond1 {
  get {
    return _cond1;
  }
  set {
    _cond1 = value;
    RaisePropertyChanged();
    RaisePropertyChanged("MergedCondition");
} 

答案 1 :(得分:1)

@Chris Eelmaa的解决方案已经足够了。

如果您不想更改视图模型,可以在子标签的可见性上使用MultiDataTrigger。

<Style TargetType="StackPanel">
    <Style.Triggers>    
      <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
          <Condition Binding="{Binding ElementName=Label1, Path=Visibility}" Value="Hidden" />
          <Condition Binding="{Binding ElementName=Label2, Path=Visibility}" Value="Hidden" />
          <Condition Binding="{Binding ElementName=Label3, Path=Visibility}" Value="Hidden" />
        </MultiDataTrigger.Conditions>
        <Setter Property="Visibility" Value="Hidden" />
      </MultiDataTrigger>
    </Style.Triggers>
</Style>

答案 2 :(得分:1)

另一种方法是使用quick converters 添加命名空间后:

xmlns:qc="clr-namespace:QuickConverter;assembly=QuickConverter"

并在App.Xaml.cs中设置快速转换器:

 public App()
        : base()
    {
        // Setup Quick Converter.
        QuickConverter.EquationTokenizer.AddNamespace(typeof(object));
        QuickConverter.EquationTokenizer.AddNamespace(typeof(System.Windows.Visibility));
    }

像这样使用它:

<StackPanel Visibility="{qc:MultiBinding '($P1 == Visibility.Visible || $P2 == Visibility.Visible || $P3 == Visibility.Visible)?Visibility.Visible:Visibility.Collapsed ', P1={Binding Path=Val1},P2={Binding Path=Val2},P3={Binding Path=Val3}}" >
    <Label Visibility="{Binding Val1}" Content="1"/>
    <Label Visibility="{Binding Val2}" Content="2"/>
    <Label Visibility="{Binding Val3}" Content="3"/>
</StackPanel>