在MVVM场景中,我想基于超链接点击或图像点击来显示/隐藏用户控件。如何在XAML中实现这一目标?
答案 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}}"/>