如何将多个元素属性绑定到wpf中的Element?

时间:2013-02-18 10:21:25

标签: wpf element-binding

<Grid x:Name="LayoutRoot">
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
        <Button Content="Button" Width="112" Height="50" Visibility="{Binding IsFocused, ElementName=textBox1,Converter={StaticResource MyConverter1}}"/>           
    </StackPanel>
    <TextBox Height="57" HorizontalAlignment="Left" Margin="144,103,0,0" Name="textBox1" VerticalAlignment="Top" Width="98" />
    <TextBox Height="57" HorizontalAlignment="Left" Margin="277,103,0,0" x:Name="textBox2" VerticalAlignment="Top" Width="88" />
    <TextBox Height="57" HorizontalAlignment="Left" Margin="390,103,0,0" x:Name="textBox3" VerticalAlignment="Top" Width="87" />        
</Grid>

使用上面的代码我可以得到以下结果。

enter image description here

如果点击 textBox1 按钮会同时隐藏我点击 textBox2 textBox3 ,按钮会隐藏。

我需要的是,每当我点击 textBox1 texBox3 时,按钮都应隐藏。 我的意思是上面一行,

<Button Content="Button" Width="112" Height="50" Visibility="{Binding IsFocused, ElementName=textBox1 or textBox3,Converter={StaticResource MyConverter1}}"/>

这可能吗?

1 个答案:

答案 0 :(得分:1)

一种方法是将MultiBindingIMultiValueConverter实施结合使用。

转换器的重要部分看起来像这样:

public class MultiConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter,
                          CultureInfo culture)
    {
        return values.Cast<bool>().Any(x => x) ?
               Visibility.Collapsed : Visibility.Visible;
    }

    public object[] ConvertBack(object value, Type[] targetTypes,
                                object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

用法如下:

<Button Content="Button" Width="112" Height="50"
        Margin="196,186,195,75">
  <Button.Visibility>
    <MultiBinding Converter="{StaticResource MultiConverter}">
      <Binding ElementName="textBox1" Path="IsFocused" />
      <Binding ElementName="textBox3" Path="IsFocused" />
    </MultiBinding>
  </Button.Visibility>
</Button>