WPF - how to hide menu item if command's CanExecute is false? WPF - how to hide menu item if command's CanExecute is false? wpf wpf

WPF - how to hide menu item if command's CanExecute is false?


Thanks for the solution. For those wanting explicit XAML this might help:

<Window.Resources>        <BooleanToVisibilityConverter x:Key="booleanToVisibilityConverter" /></Window.Resources><ContextMenu x:Key="innerResultsContextMenu">    <MenuItem Header="Open"              Command="{x:Static local:Commands.AccountOpened}"              CommandParameter="{Binding Path=PlacementTarget.DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"               CommandTarget="{Binding Path=PlacementTarget, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"              Visibility="{Binding Path=IsEnabled, RelativeSource={RelativeSource Self}, Mode=OneWay, Converter={StaticResource booleanToVisibilityConverter}}"               /></ContextMenu>

In my case, the context menu is a resource, so the binding for the visibility must use the RelativeSource Self binding setup.

As a side, for the CommandParameter, you might also pass the DataContext of the item whom was clicked to open the context menu. And in order to route the command bindings to the parent window, you will need to set the CommandTarget accordingly also.


<Style.Triggers>    <Trigger Property="IsEnabled" Value="False">        <Setter Property="Visibility" Value="Collapsed"/>    </Trigger></Style.Triggers>

CanExecute toggles the IsEnabled property so just watch this and keep everything in the UI. Create a separate style if you want to reuse this.


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    }