WPF - 如果命令的CanExecute是false,如何隐藏菜单项? [英] WPF - how to hide menu item if command's CanExecute is false?
问题描述
默认情况下,当其命令无法执行时(CanExecute = false),菜单项被禁用。基于CanExecute方法,使菜单项可见/折叠的最简单方法是什么?
By default menu items become disabled when its command cannot be executed (CanExecute = false). What is the easiest way to make the menu item visible/collapsed based on the CanExecute method?
感谢
为方便起见,这里的解决方案:使用Boolean Visibility转换器。
for your convenience here's the solution: Bind the visibility property to the IsEnabled property using "Boolean to Visibility" converter.
推荐答案
您可以简单地将Visibility绑定到IsEnabled(CanExecute == false)。
你仍需要一个IValueConverter将bool转换为visible / collapsed。
You can simply bind Visibility to IsEnabled (set to false on CanExecute == false). You still would need an IValueConverter to convert the bool to visible/collapsed.
public class BooleanToCollapsedVisibilityConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//reverse conversion (false=>Visible, true=>collapsed) on any given parameter
bool input = (null == parameter) ? (bool)value : !((bool)value);
return (input) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
这篇关于WPF - 如果命令的CanExecute是false,如何隐藏菜单项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!