Search code examples
wpfelement-binding

How to bind more than one element property to an Element in wpf?


<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>

With above code i can the following result.

enter image description here

If click textBox1 Button would hide at the same i click textBox2 and textBox3, the Button would hide.

What i need is ,Whenever i click textBox1 and texBox3, the button should be hide. what i mean with above line,

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

Is this possible ?


Solution

  • One approach would be to use MultiBinding together with a IMultiValueConverter implementation.

    The important parts of the converter would look something like this:

    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();
        }
    }
    

    Usage would be like this:

    <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>