2012-12-03 54 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中的某些內容中)。

我希望這會有所幫助。