views:

1859

answers:

2

I'm relatively new to DataBinding and just reading into it. What I want to do is the following:

I have a StackPanel with a number of child controls:

        <StackPanel Orientation="Horizontal">
            <TextBox x:Name="textbox1" Width="100">1</TextBox>
            <TextBox x:Name="textbox2" Width="100">2</TextBox>
            <TextBox x:Name="textbox3" Width="100">3</TextBox>
        </StackPanel>

The visibility property of the textboxes can be changed by code. Now, if all TextBoxes are set to Visibility=Collapsed, i also want StackPanel.Visibility set to Collapsed, but if one or more TextBoxes are shown (Visibility=Visible), StackPanel.Visibility should also be set to Visible.

Can this be achieved with a simple DataBinding or do I have to implement this functionality in C# code?

+3  A: 

Have you considered setting the visibility of the TextBoxes to Hidden? This will "hide" the space that is assigned for the TextBoxes. Assuming their are no other controls in the StackPanel, then it will not be visible.

Of course, this solution may make some naive assumptions about your implementation.

If you need the more complex scenario, I would attempt the following: Note: This is psuedocode - may not compile..

1) Use a MultiBinding

<StackPanel>
  <StackPanel.Visibility Converter={StaticResource visibilityConverter}>
    <MultiBinding.Bindings>
      <Binding ElementName="textBox1" Path="Visibility" />
      <Binding ElementName="textBox2" Path="Visibility" />
      <Binding ElementName="textBox3" Path="Visibility" />
    </MultiBinding.Bindings>
  </StackPanel.Visibility>
</StackPanel>

2) Declare the Converter

<Window.Resources>
  <local:VisibilityConverter x:Key="visibilityConverter" />
</Window.Resources>

3) Define the Converter

public class VisibilityConverter : IMultiValueConverter
{
  public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
  {
    Visibility text1Vis = (Visibility)values[0];
    Visibility text2Vis = (Visibility)values[1];
    Visibility text3Vis = (Visibility)values[2];

    if (text1Vis == text2Vis == text3Vis == Visibility.Collapsed)
      return Visibility.Collapsed;

    return Visibility.Visible;
  }
}
Brad Leach
Small error: Converter={StaticResource visibilityConverter} should go on MultiBinding.Bindings instead of Visibility
Greg R
+4  A: 

I can not think of a way to do this directly through databinding.

Personally I would have a view model behind the view, and set the views DataContext to the view model.

In the view model I would then have a property telling the view if all the textboxes are collapsed. That property would be set by code. Then bind the stackpanel visibility to that property.

(The property must either be a depandancy property, or the view model must implement INotifyPropertyChanged for the view to automatically update)

Kjetil Watnedal