2011-04-01 41 views
1

我是WPF和MVVM的初學者。 我有一個簡單的wpf窗口,其中我添加了2個值。我在添加按鈕中使​​用命令綁定 。如果驗證失敗,不要關閉窗口 - 在WPF

這裏是按鈕

<Button Content="OK" Name="btn_OK" Command="{Binding AddShutterType}" /> 

這個命令寫在我的視圖模型我的XAML代碼,也是我正在做一些驗證 但我的問題是,如果驗證失敗或成功,我的窗口不打烊! ! 如果我給「this.close」窗口按鈕單擊事件,那麼它總是關閉。 我的要求是如果驗證失敗就保留窗口,如果驗證成功則關閉。這個怎麼做?

這是我的視圖模型代碼,其中包含驗證部分。

private ICommand _AddShutterType; 

    public ICommand AddShutterType 
    { 
     get 
     { 
      if (_AddShutterType == null) 
      { 
       _AddShutterType = new DeligateCommand.DelegateCommand(delegate() 
       { 
        ShutterNameToAdd.Trim(); 
        ShutterCodeToAdd.Trim(); 

        StringBuilder SB = new StringBuilder(); 
        if (ShutterCodeToAdd == "") 
        { 
         SB.Remove(0, SB.Length); 
         SB.Append("Please type in a Code for the shutter."); 
         throw new ArgumentException(SB.ToString()); 
        } 

        if (ShutterCodeToAdd.Length > 10) 
        { 
         SB.Remove(0, SB.Length); 
         SB.Append("Shutter type code size cannot be more than 5"); 
         throw new ArgumentException(SB.ToString()); 
        } 

        if (ShutterNameToAdd == "") 
        { 
         SB.Remove(0, SB.Length); 
         SB.Append("Please type in a Name for the shutter."); 
         throw new ArgumentException(SB.ToString()); 
        }      

        Model.AddShutterType(ShutterCodeToAdd, ShutterNameToAdd); 
       }); 
      } 
      return _AddShutterType; 
     } 
    } 

請任何一個幫助我..

回答

0

我的解決辦法是舉行VM中的視圖的裁判,但是這將是一個接口;

例如。

public View : UserControl, IView 
{ 
    void IView.Close() 
    { 
     this.Close(); 
    } 
} 

public ViewModel 
{ 
    public IView View{get;set;} 

    public void CommandImpl() 
    { 
     if (Validated()) 
      View.Close(); 
    } 
} 

希望這會有所幫助。