wpf databind IsVisible to TabControl.SelectedItem != null

折月煮酒 提交于 2019-12-18 21:52:54

问题


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.



来源:https://stackoverflow.com/questions/1158494/wpf-databind-isvisible-to-tabcontrol-selecteditem-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!