views:

803

answers:

2

I have a stackpanel which I want to make visible only when SomeTabControl.SelectedItem is not null - how do I do this in WPF binding?

+1  A: 

Create a converter that converts a nullable value to a System.Windows.Visibility value and use that on your binding.

For instance:

<StackPanel x:Name="myPanel" Visibility="{Binding Path=SelectedItem, Mode=OneWay, ElementName=SomeTabControl, Converter={StaticResource visibilityConverter}}" />

Code for the converter class:

public class VisibilityConverter : IValueConverter
{
    #region [ IValueConverter ]

    public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
    {
        if( value == null )
            return System.Windows.Visibility.Collapsed;

        return System.Windows.Visibility.Visible;
    }

    public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
    {
        throw new NotSupportedException( );
    }

    #endregion
}

P.S. This assumes that in your control's XAML there is a static resource named visibilityConverter.

azazeal
You can use the built in BoolToVisiblityConverter instead of writing your own. http://msdn.microsoft.com/en-us/library/system.windows.controls.booleantovisibilityconverter.aspx
Andy
How can the BoolToVisibilityConverter convert !=null to Visible? If it was either true or false I get it. But != null?
azazeal
+1  A: 

You can do it without a converter using a style and trigger:

<StackPanel>
    <StackPanel.Style>
        <Style TargetType="{x:Type StackPanel}">
            <Setter Property="Visibility" Value="Visible" />
            <Style.Triggers>
                <DataTrigger
                    Binding="{Binding SelectedItem,ElementName=tabControl1}" 
                    Value="{x:Null}">
                    <Setter Property="Visibility" Value="Hidden" />
                </DataTrigger>
            <Style.Triggers>
        </Style>
    </StackPanel.Style>
</StackPanel>

So that shows the StackPanel by default, but then hides it when the SelectedItem on tabControl1 is null.

Matt Hamilton
Excellent, thanks!
Peter Morris