2016-05-23 115 views
0

我想添加一個上下文菜單到我創建的WPF用戶控件。菜單,圖標和命令顯示,但在菜單中顯示爲灰色,即使我已將CommandBinding_CanExecute設置爲一直返回true。添加上下文菜單與RoutedUICommand wpf用戶控件

這裏是XAML

<UserControl x:Class="KeyframePartialApp.ctrCell" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:local="clr-namespace:KeyframePartialApp" 
     mc:Ignorable="d"> 

<UserControl.Resources> 
    <RoutedUICommand x:Key="MakeKeyCell" Text="Make KeyCell" /> 
</UserControl.Resources> 


<Border x:Name="bdrBackground" Width="14" Height="24" BorderBrush="{DynamicResource {x:Static SystemColors.ControlDarkDarkBrushKey}}" BorderThickness="1" Background="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" > 
    <Border.ContextMenu> 
     <ContextMenu> 
      <MenuItem Icon="{StaticResource imgKeyIcon}" Command="{StaticResource MakeKeyCell}"></MenuItem> 
     </ContextMenu> 
    </Border.ContextMenu> 
    <Border.CommandBindings> 
     <CommandBinding Command="{StaticResource MakeKeyCell}" CanExecute="CommandBinding_CanExecute" Executed="MakeKeyCell_Executed"></CommandBinding> 
    </Border.CommandBindings> 
    <Rectangle Width="10" Height="10" x:Name="rctIcon" /> 
</Border> 

,這裏是背後

public partial class ctrCell : UserControl 
{ 
    private Cell _cell; 

    public ctrCell(Cell cell) 
    { 
     _cell = cell; 
     InitializeComponent(); 
     _cell.PropertyChanged += _cell_PropertyChanged; 
     UpdateKeyCellImage(); 
    } 

    private void _cell_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) 
    { 
     if (e.PropertyName == "isKeyCell") UpdateKeyCellImage(); 
    } 

    public void UpdateKeyCellImage() 
    { 
     if (_cell.isKeyCell) 
     { 
      rctIcon.Fill = (ImageBrush)Application.Current.Resources["ibKeycell"]; 
     } 
     else 
     { 
      rctIcon.Fill = null; 
     } 
    } 

    private void MakeKeyCell_Executed(object sender, ExecutedRoutedEventArgs e) 
    { 
     _cell.isKeyCell = true; 

    } 

    private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) 
    { 
     if (!_cell.isKeyCell) e.CanExecute = true; 
    } 
} 

代碼}

回答

0

這是一個重複:WPF custom command in context menu are disabled until any button clicked

隨着信貸由西蒙D.答案,爲了完整,我會在這裏太回答:

更詳細的解釋可以在這裏找到: http://www.wpftutorial.net/RoutedCommandsInContextMenu.html

爲了解決您的問題,只需將CommandTarget添加到您的菜單項:

<Border.ContextMenu> 
    <ContextMenu> 
     <MenuItem IsEnabled="True" 
        Command="{StaticResource MakeKeyCell}" 
        CommandTarget="{Binding Path=PlacementTarget, 
              RelativeSource={RelativeSource FindAncestor, 
              AncestorType={x:Type ContextMenu}}}" /> 
    </ContextMenu> 
</Border.ContextMenu>