我有一个Grid
的窗口:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0.5*" />
<RowDefinition Height="40" />
<RowDefinition Height="15*" />
<RowDefinition Height="0.3*" />
</Grid.RowDefinitions>
<central:CentralView Grid.Row="2" ItemsSource="{Binding MainWindowModels}" />
</Grid>
CentralView是带有DataGrid和DataGrid ContextMenu的UserControl。此外,我有简单的类巫婆实现ICommand接口和静态命令类,其中存储所有命令:
static CentralViewBaseCommands _goToEti;
public static CentralViewBaseCommands GoToEti => _goToEti ?? new
CentralViewBaseCommands(GoToExternalWindow);
private static void GoToExternalWindow(object obj)
{
if (obj is GridContextMenuInfo)
{
object record = (obj as GridRecordContextMenuInfo)?.Record;
CentralDataGridModel mwSfDgModel = (CentralDataGridModel)record;
if (mwSfDgModel != null)
{
//TODO
}
}
}
CentralViewBaseCommands:
public class CentralViewBaseCommands : ICommand
{
private Action<object> _execute;
private Predicate<object> _canExecute;
public CentralViewBaseCommands(Action<object> execute) : this(execute, null)
{
_execute = execute;
}
public CentralViewBaseCommands(Action<object> execute,Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException(nameof(execute));
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute?.Invoke(parameter) ?? true;
}
public void Execute(object parameter)
{
_execute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
以下是MenuItem的代码(位于UserControl中):
<MenuItem Header="Исправление ошибок">
<MenuItem Command="{Binding Source={x:Static Member=command:CentralViewCommands.GoToEti}}"
CommandParameter="{Binding}"
Header="Удаление ошибочно внесенной техники">
<MenuItem.Icon>
<Viewbox>
<Grid>
<Grid Width="32"
Height="32"
Visibility="Collapsed" />
<Path Width="26"
Height="26"
Margin="0,0,0,0"
Fill="#FFFF0000"
RenderTransformOrigin="0.5,0.5"
Stretch="Uniform">
<Path.RenderTransform>
<TransformGroup>
<TransformGroup.Children>
<RotateTransform Angle="0" />
<ScaleTransform ScaleX="1" ScaleY="1" />
</TransformGroup.Children>
</TransformGroup>
</Path.RenderTransform>
</Path>
</Grid>
</Viewbox>
</MenuItem.Icon>
</MenuItem>
</MenuItem>
所以,问题是如下。当我点击按照我的预期执行的菜单项命令时,但是如果我将命令绑定到UserControl
ViewModel (DelegateCommand<>) Command="{Binding CommandInViewModel}"
中的命令,则不会发生任何事情并且命令不会执行。
有人能解释我为什么吗?
答案 0 :(得分:1)
我认为这是因为这一行:
public static CentralViewBaseCommands GoToEti => _goToEti ?? new CentralViewBaseCommands(GoToExternalWindow);
始终生成CentralViewBaseCommands
的新实例。
请改为尝试:
public static CentralViewBaseCommands GoToEti { get; } = new CentralViewBaseCommands(GoToExternalWindow);
并删除_goToEti
。
希望它有所帮助!