【发布时间】:2017-08-06 07:05:39
【问题描述】:
我有一个带有“MainView”和一些嵌套视图的 Catel 应用程序。
嵌套视图有一个ListView,一些项目有一个ContextMenu,还有一些MenuItems。
在 MainView 的 ViewModel 中,我创建了一个 TaskCommand<object>,它将对传递的参数执行一些操作。这个传递的参数应该是ListView 的当前SelectedItem。该命令正在全局注册到ICommandManager。
如果我使用ICommandManager 中的绑定命令单击MenuItem,则传递的参数将始终为null。
这里是相关代码:
NestedView.xaml:
<catel:UserControl
x:Name="UserControl"
x:Class="My.NameSpace.Views.View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:catel="http://catel.codeplex.com">
...
<ListView ItemsSource="{Binding Items}"
BorderThickness="0"
SelectedItem="{Binding SelectedItem}"
HorizontalContentAlignment="Stretch">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock VerticalAlignment="Center"
Margin="2.5"
Text="{Binding Description}">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Do Stuff"
Command="{catel:CommandManagerBinding DoStuffCommand}"
CommandParameter="{Binding DataContext.SelectedItem, ElementName=UserControl}" />
...
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListView>
...
</catel:UserControl>
MainViewModel.cs:
public class MainViewModel : ViewModelBase {
...
public ICommand DoStuffCommand { get; }
public MainViewModel(ICommandManager commandManager, IUIVisualizerService uiVisualizerService, IMessageService messageService)
{
...
DoStuffCommand = new TaskCommand<object>(OnDoStuffCommandExecute);
commandManager.CreateCommand(nameof(DoStuffCommand));
commandManager.RegisterCommand(nameof(DoStuffCommand), DoStuffCommand, this);
}
private async Task OnDoStuffCommandExecute(object parameter)
{
// command needs to be in the MainViewModel because there will be some modification on the MainView based on parameter (adding tabs, etc)
Debugger.Break();
}
...
}
如果您需要更多代码,我也可以发布此内容,但这应该足够了。
我还查看了 Catel 的 CommandManager 实现并发现了这个:
/// <summary>
/// Executes the command.
/// </summary>
/// <param name="commandName">Name of the command.</param>
/// <exception cref="ArgumentException">The <paramref name="commandName"/> is <c>null</c> or whitespace.</exception>
/// <exception cref="InvalidOperationException">The specified command is not created using the <see cref="CreateCommand"/> method.</exception>
public void ExecuteCommand(string commandName)
{
Argument.IsNotNullOrWhitespace("commandName", commandName);
lock (_lockObject)
{
Log.Debug("Executing command '{0}'", commandName);
if (!_commands.ContainsKey(commandName))
{
throw Log.ErrorAndCreateException<InvalidOperationException>("Command '{0}' is not yet created using the CreateCommand method", commandName);
}
_commands[commandName].Execute(null);
}
}
我假设如果我单击 MenuItem 会调用此方法并解释该行为。
是否有任何适当的解决方案/解决方法可以将(绑定)参数传递给我的 OnExecute 方法?
提前致谢
【问题讨论】: