wpf数据绑定TabControl.SelectedItem的IsVisible!= null

时间:2009-07-21 10:56:24

标签: wpf data-binding visibility

我有StackPanel我希望仅在SomeTabControl.SelectedItem != null时才能看到它。我如何在WPF绑定中执行此操作?

2 个答案:

答案 0 :(得分:13)

您可以使用样式和触发器在没有转换器的情况下执行此操作:

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

此示例默认显示StackPanel,但是当tabControl1上的SelectedItem为null时隐藏它。

答案 1 :(得分:5)

创建一个转换器,将可空值转换为System.Windows.Visibility值,并在绑定时使用该值。

例如:

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

转换器类的代码:

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。这假设在控件的XAML中有一个名为 visibilityConverter 的静态资源。