如何在wpf mvvm中隐藏/显示堆栈面板

时间:2013-10-14 09:26:04

标签: wpf xaml mvvm

在MVVM场景中,我想基于超链接点击或图像点击来显示/隐藏用户控件。如何在XAML中实现这一目标?

3 个答案:

答案 0 :(得分:15)

使用切换按钮并使用UserControl绑定BooleanToVisibilityConverter的可见性:

定义资源:

<BooleanToVisibilityConverter x:Key="BoolToVisibility" />

切换按钮:

<ToggleButton x:Name="VisibilityToggle>
    <Image Source="..." />
</ToggleButton>

用户控件:

<MyControl Visibility="{Binding IsChecked, ElementName=VisibilityToggle, Converter={StaticResource BoolToVisibility}}" />

答案 1 :(得分:4)

使用Visibility

BooleanToVisibilityConverter属性绑定到ViewModel的bool属性
<Window.Resources>
    <BooleanToVisibilityConverter x:Key="visibilityConverter" />
</Window.Resources>

...

<MyUserControl Visibility="{Binding IsMyUserControlVisible, Converter={StaticResource visibilityConverter}}" />

视图模型:

private bool _isMyUserControlVisible;
public bool IsMyUserControlVisible
{
    get { return _isMyUserControlVisible; }
    set
    {
        _isMyUserControlVisible = value;
        OnPropertyChanged("IsMyUserControlVisible");
    }
}

答案 2 :(得分:0)

假设您在ViewModel中有一个布尔属性,用于确定是否显示控件

public bool DisplayControl { get; set; }

使用StackPanel

绑定BooleanToVisibiltyConverter的可见性
<Window.Resources>
   <BooleanToVisibilityConverter x:Key="visibilityConverter" />
</Window.Resources>

你的控制:

<StackPanel Visibility="{Binding DisplayControl, Converter={StaticResource visibilityConverter}}"/>