我正在尝试将上下文菜单添加到我创建的WPF用户控件中。菜单,图标和命令显示但在菜单中它显示为灰色,即使我已将CommandBinding_CanExecute设置为总是返回true。
这是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 :(得分:0)
这是:WPF custom command in context menu are disabled until any button clicked
的副本赞同Simon D.的回答,为了完整起见,我也会在这里回答:
可以在此处找到更详细的解释: http://www.wpftutorial.net/RoutedCommandsInContextMenu.html
要解决您的问题,只需将CommandTarget添加到您的MenuItem:
<Border.ContextMenu>
<ContextMenu>
<MenuItem IsEnabled="True"
Command="{StaticResource MakeKeyCell}"
CommandTarget="{Binding Path=PlacementTarget,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ContextMenu}}}" />
</ContextMenu>
</Border.ContextMenu>