2012-12-03 53 views
3

我是WPF和MVVM的新手,所以对我很感兴趣。使用WPF验证命令

基本上,我正在创建一个应用程序以使用户能够将他们的组织详细信息输入到数据库中。

我创造我的WPF应用程序中,我有一个View Model包含propertiescommandsentity framework方法(我知道这是不使用MVVM正确的方式,但我慢慢学会如何去实现它) 。

在我的观点之一,它是一个选项卡控件,允许用户输入不同的组织详细信息到数据库中,然后,在另一个视图上,我有一个数据网格来显示他们输入的内容以使用户在需要时更新内容。

这导致我的问题。到目前为止,我已经验证了我的命令,以便当某些字段为空时,该按钮将不会被激活,但是一旦它们被输入,它们将被激活。像这样;

  private ICommand showAddCommand; 
    public ICommand ShowAddCommand 
    { 
     get 
     { 
      if (this.showAddCommand == null) 
      { 
       this.showAddCommand = new RelayCommand(this.SaveFormExecute, this.SaveFormCanExecute);//i => this.InsertOrganisation() 
      } 

      return this.showAddCommand; 
     } 
    } 

    private bool SaveFormCanExecute() 
    { 
     return !string.IsNullOrEmpty(OrganisationName) && !string.IsNullOrEmpty(Address) && !string.IsNullOrEmpty(Country) && !string.IsNullOrEmpty(Postcode) 
      && !string.IsNullOrEmpty(PhoneNumber) && !string.IsNullOrEmpty(MobileNumber) && !string.IsNullOrEmpty(PracticeStructure) && !string.IsNullOrEmpty(PracticeType) && !string.IsNullOrEmpty(RegistrationNumber); 
    } 

    private void SaveFormExecute() 
    { 
     InsertOrganisations(); 
    } 

    Xaml: 
    <Button Content="Save" Grid.Column="1" Grid.Row="18" x:Name="btnSave" VerticalAlignment="Bottom" Width="75" Command="{Binding ShowAddCommand}"/> 

但我希望能实现的是,一旦用户已经进入了1个组织到数据库中,那么该命令不被激活干脆防止用户意外进入另一个组织。目的是只允许添加1个组织,不多也不少。

这可能吗?

+0

不知道这是你在找什么,所以我把它作为评论发布。我认为你需要的是每个表单验证。看看这篇文章(http://www.scottlogic.co.uk/blog/colin/2009/01/bindinggroups-for-total-view-validation/)。 – dowhilefor

+0

感谢您的回复。那么,我的领域已经验证使用属性验证,所以这不是问题。我只想要一种能够验证我的命令的方法,因此它只允许输入一行数据(在数据库中),可能使用标志?但我不知道如何实现这一点。 –

+0

为什么不将IsEnabled属性绑定到您调用的属性bool HasOrganisation {return mOrganisation.Count> 0;}如果组织属性发生更改,则引发此问题。它很难给你一个很好的答案,没有关于你的代码的更多信息。最好给我们一个你想做什么的非常小的可运行的例子。 – dowhilefor

回答

0

两件事。 1),我建议编辑RelayCommand如下所采取的措施:

private Action<object> _execute; 
    private Predicate<object> _canExecute; 

    public RelayCommand(Action<object> execute, Predicate<object> canExecute) 
    { 
     if (execute == null) 
      throw new ArgumentNullException("execute"); 
     _execute = execute; 
     _canExecute = canExecute; 
    } 

    //[DebuggerStepThrough] 
    public bool CanExecute(object parameter) 
    { 
     return _canExecute == null ? true : _canExecute(parameter); 
    } 

这可能不会帮助你的眼前问题,但它会让你的代码的可重用性,你就可以结合一定的你的ICommand中的View的参数作为CanExecute测试和执行的参数(或者如果你不需要这个参数,只需在ICommand.Execute中传递null作为对象参数,并且不要将任何东西绑定到View中的CommandParameter)

此外,在您的RelayCommand中,请确保您覆盖了CanExecuteChanged,如下所示:

public override event EventHandler CanExecuteChanged 
    { 
     add { CommandManager.RequerySuggested += value; } 
     remove { CommandManager.RequerySuggested -= value; } 
    } 

这将触发你的ICommand在用户进行更改时(并且很可能是你缺失的那部分)重新检查CanExecute。

最后,一旦完成,只需将您的条件包含在CanExecute中(无论是从CommandParameter还是从VM中的某些内容中)。

我希望这会有所帮助。