我有两个菜单项元素 - “Undelete”和“Delete”具有互补可见性:当显示一个时,另一个被隐藏。
在ViewModel的代码中,我有一个依赖属性FilesSelectedCanBeUndeleted定义如下:
private bool _filesSelectedCanBeUndeleted;
public bool FilesSelectedCanBeUndeleted
{
get
{
return _filesSelectedCanBeUndeleted;
}
set
{
_filesSelectedCanBeUndeleted = value;
OnPropertyChanged("FilesSelectedCanBeUndeleted");
}
}
Undelete按钮的XAML如下所示:
<MenuItem Header="Undelete" Command="{Binding UndeleteCommand }"
Visibility="{Binding Path=FilesSelectedCanBeUndeleted,
Converter={StaticResource BoolToVisConverter}}" >
正如您所见,Undelete的Visibility绑定到FilesSelectedCanBeUndeleted property(在BooleanToVisibilityConveter的帮助下)。
现在我的问题是,如何编写XAML以将Delete按钮的Visibility绑定到FilesSelectedCanBeUndeleted属性的“NOT”值?
谢谢,
答案 0 :(得分:5)
Here是自定义IValueConverter的示例,它允许您反转可见性逻辑。基本上,当view-model属性为true时,一个MenuItem将可见,而另一个将被折叠。
所以你需要像这样定义转换器的两个实例:
<local:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<local:BooleanToVisibilityConverter x:Key="ReversedBooleanToVisibilityConverter" IsReversed="true" />
答案 1 :(得分:3)
你可以使用将datatrigger应用到menuitem以避免你的viemodel中的另一个属性 -
<MenuItem Header="Delete"
Command="{Binding DeleteCommand }">
<MenuItem.Style>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Visibility" Value="Visible" />
<Style.Triggers>
<DataTrigger Binding="{Binding FilesSelectedCanBeUndeleted}" Value="False">
<Setter Property="Visibility"
Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
</MenuItem.Style>
</MenuItem>
答案 2 :(得分:1)
在ViewModel上创建新属性,然后取消'FilesSelectedCanBeUndeleted',然后绑定到它。
答案 3 :(得分:0)
我刚才做了类似的事情,只是简单地否定了......
private bool _filesSelectedCanBeUndeleted;
public bool FilesSelectedCanBeUndeleted{
get{
return _filesSelectedCanBeUndeleted;
}
set{
_filesSelectedCanBeUndeleted = value;
OnPropertyChanged("FilesSelectedCanBeUndeleted");
// You have also to notify that the second Prop will change
OnPropertyChanged("FilesSelectedCanBeDeleted");
}}
public bool FilesSelectedCanBeDeleted{
get{
return !FilesSelectedCanBeUndeleted;
}
}
Xaml看起来就像这样......
<MenuItem Header="Delete"
Command="{Binding DeleteCommand }"
Visibility="{Binding Path=FilesSelectedCanBeDeleted, Converter={StaticResource BoolToVisConverter}}" >