wpf databind IsVisible to TabControl.SelectedItem

2019-02-12 16:47发布

问题:

I have a StackPanel which I want to make visible only when SomeTabControl.SelectedItem != null. How do I do this in WPF binding?

回答1:

You can do it without a converter by 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>

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



回答2:

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.