代码之家  ›  专栏  ›  技术社区  ›  James Cadd

WPF-处理ViewModel中的应用程序命令

  •  6
  • James Cadd  · 技术社区  · 16 年前

    我打赌这个问题已经被回答了很多次了,但是。。。

    编辑:如果可能的话,我想用库存的WPF来解决这个问题。我知道这类东西有很多可用的框架,但是我希望代码保持简单。

    EDIT2:包括一些示例代码。

    <UserControl>
      <UserControl.DataContext>
        <local:MyViewModel/>
      </UserControl.DataContext>
    
      <Button Command="Find"/>
    </UserControl>
    

    哪里:

    class MyViewModel
    {
      // Handle commands from the view here.
    }
    

    我可以向UserControl添加一个CommandBinding来处理Executed,然后在MyViewModel中调用一个假想的Find方法来执行实际的工作,但是这是额外的和不必要的代码。我更喜欢ViewModel本身处理Find命令。一个可能的解决方案是让MyViewModel从UIElement派生,但这似乎违反直觉。

    1 回复  |  直到 16 年前
        1
  •  4
  •   Vlad    16 年前

    命令的目的是将生成命令的代码与执行命令的代码解耦。因此:如果您想要紧密耦合,最好通过事件:

    <UserControl ... x:Class="myclass">
        ...
        <Button Click="myclass_find" .../>
        ...
    </UserControl>
    

    对于松耦合,需要添加 CommandBinding UserControl :

    <UserControl ... >
        <UserControl.DataContext>
            <local:MyViewModel/>
        </UserControl.DataContext>
    
        <UserControl.CommandBindings>
            <Binding Path="myFindCommandBindingInMyViewModel"/>
        </UserControl.CommandBindings>
        ...
        <Button Command="ApplicationComamnd.Find" .../>
        ...
    </UserControl>
    

    (不确定语法)

    或者你可以添加一个 给你的 用户控件 CommandBindings 在构造函数中,从ViewNodel获取值:

    partial class MyUserControl : UserControl
    {
        public MyUSerControl()
        {
            InitializeComponent();
            CommandBinding findCommandBinding = 
                      ((MyViewModel)this.DataContext).myFindCommandBindingInMyViewModel;
            this.CommandBindings.Add(findCommandBinding);
        }
    }