WPF,C#和MVVM公开命令

时间:2011-05-03 23:36:53

标签: mvvm c#-4.0 binding

大家好我想尝试使用MVVM,但我很难:(首先是我的问题,我使用this MVVM article中提供的代码作为模板我的学习。 我的问题很简单,如何公开独立命令,在这种情况下,他创建了一个超链接列表,但我如何创建一个固定的单个按钮,并与“创建新客户”链接相同。 我创建了这样的东西(已添加到MainWindowViewModel.cs):

   public CommandViewModel exposedCommand
    {
        get
        {
             return new CommandViewModel(
              Strings.MainWindowViewModel_Command_CreateNewCustomer,
              new RelayCommand(param => this.CreateNewCustomer())
              );
        }
    }

然后在xaml文档中我创建了一个新按钮,这个被添加到MainWindow.xaml

         <Button 
            Content="Button" 
            Height="23" 
            HorizontalAlignment="Left" 
            Margin="6,303,0,0" Name="button1" VerticalAlignment="Top" Width="150"
            Command="{Binding Path=exposedCommand}"
        />

我不确定我是否遗漏了什么,或者我错在哪里, Soz如果我听起来有点天真,我刚刚开始使用MVVM和路由命令等等。 哦,它确实加载链接它只是不创建选项卡,换句话说,如果你要添加

Console.Writeline("HERE"); 

到exposedCommand方法 它会打印出'HERE',当你点击按钮时它就不会做任何事情。 谢谢任何帮助都会非常感激。

3 个答案:

答案 0 :(得分:2)

您的XAML代码是正确的。 我还从Josh Smith的MVVM文章开始。 下面是我在ViewModels中实现命令的一个精简示例:

public class ProjectViewModel : ViewModelBase
{
    // Private variable for holding save command
    private RelayCommand _saveCommand;

    // Other fields here

    // Constructors and properties and stuff here

    // Command Property for Save button. Bind XAML to "SaveCommand"
    public ICommand SaveCommand
    {
        get
        {
            if (_saveCommand == null) // Init command on first get
                _saveCommand = new RelayCommand(param => this.SaveChanges(), param => this.CanSave);

            return _saveCommand;
        }
    }

    /// <summary>
    /// Method called when save command is executed
    /// </summary>
    private void SaveChanges()
    {
        // Save logic here...
    }

    /// <summary>
    /// Predicate for determining if SaveCommand is enabled
    /// </summary>        
    private bool CanSave
    {
        get
        {
            return true; // Replace with SaveCommand predicate logic
        }
    }
}

如果仍然无效,请检查BindingErrors的运行时输出。如果存在BindingError意味着View无法找到SaveCommand,则ViewModel未正确设置为View的DataContext。如果这是问题,请在评论中告诉我。

答案 1 :(得分:0)

您只能将命令绑定到那些具有ICommand接口实现的对象。

在您的示例中,您将与视图模型对象绑定。

而不是在视图模型中创建一个属性,它是一种RelayCommand并将其与按钮绑定。

它应该有用。

答案 2 :(得分:0)

关注我的第一件事是你的属性getter中的代码。您将返回一个新对象每次访问exposedCommand。这不是真的推荐,你应该把它存储在这样的支持属性中:

CommandViewModel _exposedCommand;
public CommandViewModel exposedCommand
{
  get
  {
     if (_exposedCommand == null)
     {
       _exposedCommand = new CommandViewModel(
       Strings.MainWindowViewModel_Command_CreateNewCustomer,
       new RelayCommand(param => this.CreateNewCustomer()));
     }
     return _exposedCommand;
  }
}

据说,呈现您想要的ICommand财产的典型方式是这样的:

RelayCommand _exposedCommand;
public ICommand exposedCommand
{
    get
    {
        if (_exposedCommand == null)
            _exposedCommand= new RelayCommand(param => this.CreateNewCustomer());
        return _exposedCommand;
    }
}