【问题标题】:Command to call method from viewmodel从视图模型调用方法的命令
【发布时间】:2012-06-19 02:03:07
【问题描述】:

好的,我倾向于避免使用命令,因为它们总是设法让我感到困惑,但我正在进行一个新项目,并且正在尝试正确地构建它,而我的视图中没有代码。基本上,我现在要做的就是连接一个按钮,该按钮触发一个在我的视图模型上执行某些操作的命令,并且不知何故,如此简单的事情仍然给我带来了麻烦。我想我已经很近了,但还不能完全到达那里。这是我现在拥有的。

<Window.Resources>
    <RoutedUICommand x:Key="GetMusic" />
</Window.Resources>
<Window.DataContext>
    <core:ViewMain />
</Window.DataContext>
<Window.CommandBindings>
    <CommandBinding Command="{StaticResource GetMusic}" Executed="GetMusicExecuted"/>
</Window.CommandBindings>

而视图模型现在几乎什么都不是

public class ViewMain
{
    public MusicCollection Music { get; set; }

    private void GetMusicExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        //Logic
    }
}

现在我要做的是连接我在命令绑定中设置的这个命令,以便在我的视图模型中调用我执行的方法,但是它试图在视图本身中找到该方法。有没有办法可以将它定向到我的视图模型中的方法,或者有更好的方法来设置它来完成同样的事情?希望一开始能保持简单,以免我过早地大惊小怪。

【问题讨论】:

  • 您需要通过 xaml 或后面的代码设置绑定
  • 您是否考虑过在 Prism 等标准 MVVM 框架中使用 DelegateCommands?我认为它使命令变得更加容易,因为您的命令驻留在 VM 中,您可以绑定它而无需定义 CommandBindings。

标签: c# wpf xaml mvvm command


【解决方案1】:

我倾向于使用自己的命令类,实现 ICommand。然后我将 Button Command 属性绑定到我的视图模型中的 command 属性。单击按钮时,它会执行绑定到 Command 属性的 Execute 方法。

这是丑陋的两分钟版本,但它展示了如何创建一个 Command 类,然后将其分配给您在视图模型上喜欢的任何方法的委托。

视图模型:

public class MyViewModel
{
    public MyCommand ActionCommand
    {
        get;
        set;
    }

    public MyViewModel()
    {
        ActionCommand = new MyCommand();
        ActionCommand.CanExecuteFunc = obj => true;
        ActionCommand.ExecuteFunc = MyActionFunc;
    }

    public void MyActionFunc(object parameter)
    {
        // Do stuff here 
    }

}

public class MyCommand : ICommand 
{
    public Predicate<object> CanExecuteFunc
    {
        get;
        set;
    }

    public Action<object> ExecuteFunc
    {
        get;
        set;
    }

    public bool CanExecute(object parameter)
    {
        return CanExecuteFunc(parameter);
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        ExecuteFunc(parameter);
    }
}

View 将因此绑定到它(假设 DataContext 设置为视图模型的实例):

<Window x:Class="exp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Command="{Binding Path=ActionCommand}">Action</Button>
    </Grid>
</Window>

【讨论】:

  • 看起来不错,在这种情况下,您是否使用 MyCommand 作为每个命令的基础,因为您可以为每个命令发送不同的函数来执行?
  • 在这种情况下,是的。如果您只想调用视图模型上的现有方法,则不必创建许多不同的命令类。如果你愿意,你可以创建不同的命令。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-01
  • 2015-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多