如何在视图模型中的视图上使用路由命令
我试图在我的视图上使用 RoutedCommand,以便我可以使用 CanExecute 功能,但我可以让它工作的唯一方法是使用 Prism 中的 DelegateCommand。当我尝试使用 RoutedCommand 时,按钮保持不活动状态,并且 CanExecute 函数永远不会被使用。
我尝试在 XAML 上放置 CommandBinding,但这给出了“只有生成的或代码隐藏类上的实例方法才有效”。错误。这是该代码:
<Window.CommandBindings>
<CommandBinding Command="AddCommand"
Executed="my:SettingsDialogViewModel.AddCommandMethod"
CanExecute="my:SettingsDialogViewModel.AddCommandMethodCanExecute" />
</Window.CommandBindings>
我还尝试在代码中设置 CommandBinding,但这也没有帮助。我只是不确定如何让它工作,缺少将其粘贴在代码隐藏中,或者实现一些我在网上找到的看起来极其复杂的东西。
感谢您的帮助:)
编辑: 以下是我尝试使用的方法:
public void AddCommandMethod()
{
if (SelectedMain != null)
{
SelectedMain.IsDirty = true;
_faveAppList.Add(SelectedMain);
SelectedMain.ListOrder = _faveAppList.Count;
_mainAppList.Remove(SelectedMain);
_listDirty = true;
}
}
public void AddCommandMethodCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
I am trying to use a RoutedCommand on my view so that I can use the CanExecute functionality, but the only way I can get it to work is with a DelegateCommand from Prism. When I try to use the RoutedCommand the button stays inactive and the CanExecute function never gets used.
I've tried putting a CommandBinding on my XAML but that gives a "Only instance methods on the generated or code-behind class are valid." error. Here is that code:
<Window.CommandBindings>
<CommandBinding Command="AddCommand"
Executed="my:SettingsDialogViewModel.AddCommandMethod"
CanExecute="my:SettingsDialogViewModel.AddCommandMethodCanExecute" />
</Window.CommandBindings>
I've also tried setting up a CommandBinding in code, but that doesn't help either. I'm just not sure how to get it to work, short of sticking it in the code-behind, or implementing some ridiculously complicated looking thing I've found on the web.
Thanks for any help :)
EDIT:
Here are the methods I am trying to use:
public void AddCommandMethod()
{
if (SelectedMain != null)
{
SelectedMain.IsDirty = true;
_faveAppList.Add(SelectedMain);
SelectedMain.ListOrder = _faveAppList.Count;
_mainAppList.Remove(SelectedMain);
_listDirty = true;
}
}
public void AddCommandMethodCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是正确的 MVVM 表示法。我将提供一种方法来做到这一点。
That isn't the proper MVVM notation. I'll provide one way of doing this.
更好的选择是实现
ICommand< /code>
接口并在实现的方法中编写逻辑。然后你的视图模型可以返回你的自定义命令,你可以从你的视图绑定到它。
这会将实际的命令实现与视图模型分开,但您仍然可以在视图模型中很好地实现逻辑。
像这样的事情:
然后只需绑定发出命令的控件即可。
A better option would be to implement the
ICommand
interface and write your logic in the implemented methods. Then your view model can return your custom command and you could just bind to it from your view.This will separate the actual command implementation from your view model but you can still nicely implement the logic within your view model.
Something like this:
Then just bind controls that issues the command.