0

我尝试了两种不同的从 ViewModel 在 WPF 中进行命令的方法,但都失败了。如果我将其放入视图中,顶级方法效果很好,但有人告诉我这是不好的做法。我被告知的第二种方法是在 MVVM 中执行自定义命令的正确方法,但是我陷入了如何从视图中实际调用/绑定命令的问题。

查看型号:

class MainViewModel : INotifyPropertyChanged
{

    #region INPC
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion


     public readonly static RoutedUICommand myCommand;

    static MainViewModel()
    { 
        myCommand = new RoutedUICommand("customCommand","My Command",typeof(MainViewModel));

    }

    private void ExecutemyCommand(object sender, ExecutedRoutedEventArgs e)
    {

        MessageBox.Show("textBox1 cleared");
    }

    private void myCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }
}

在我的视图中,我有这个代码,这给了我一个错误

<Window x:Class="ConfigManager2.View.MainView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:con="clr-namespace:ConfigManager2.Converters"
    xmlns:vm="clr-namespace:ConfigManager2.ViewModel"
    xmlns:local="clr-namespace:ConfigManager2.View"
.
.
.
<Window.CommandBindings>
    <CommandBinding
        Command="{x:Static vm:MainViewModel.myCommand}"
        CanExecute="myCommandCanExecute"
        Executed="ExecutemyCommand" />
</Window.CommandBindings>
.
.
.
 <Button Content="COMMAND ME" Height="50px"  Command="{x:Static vm:MainViewModel.myCommand}" />

我得到的错误是“ConfigManager2.View.MainView”不包含“ExecutemyCommand”的定义,并且找不到接受“ConfigManager2.View.MainView”类型的第一个参数的扩展方法“ExecutemyCommand”(您是否缺少使用指令还是程序集引用?)

我尝试了另一种使用 ICommand 的方法,但对于如何将其绑定到 XAML 中的上述按钮感到困惑

视图模型:

    public ICommand ClearCommand { get; private set; }
public MainViewModel()
{
    ClearCommand= new ClearCommand(this);
}



class ClearCommand : ICommand
{
    private MainViewModel viewModel;

    public ClearCommand(MainViewModel viewModel)
    {
        this.viewModel = viewModel;
    }

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

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        viewModel.vmTextBox1 = String.Empty;
        MessageBox.Show("Textbox1 Cleared");
    }
}
4

1 回答 1

1

使用 ICommand 版本(我更喜欢),您可以直接绑定到命令:

<Button Command="{Binding ClearCommand}"/>

没有必要的 Window.CommandBinding。如果将 MainViewModel 的实例设置为窗口或按钮的 ,则此方法有效DataContext

于 2012-08-29T11:40:33.837 回答