2017-08-17 44 views
0

我必須有TimePicker和驗證規則WPF DelegateCommand和ValidationRules

<controls:TimePicker Grid.Row="0" Grid.Column="1" Culture="Ru-ru" Margin="5,5,5,2.5"> 
      <controls:TimePicker.SelectedTime> 
       <Binding Path="EditTimeStart" Mode="TwoWay" NotifyOnValidationError="True" > 
        <Binding.ValidationRules> 
         ...... 
        </Binding.ValidationRules> 
       </Binding> 
      </controls:TimePicker.SelectedTime> 
     </controls:TimePicker> 

和一個按鈕( 「保存」)。

<Button Content="Save" Command="{Binding Path=SaveCommand}"/> 

在我的視圖模型

SaveCommand = new DelegateCommand(Save, CanSave); 

其中CanSave方法過程的另一сonditions(條件不與ValidationRules相交)

問題。我可以SaveButton啓用綁定到validationriles和CanSave方法嗎?

+0

由於這個特殊原因,在UI中進行驗證是一個糟糕的主意。更好地實施INotifyDataErrorInfo,它會在UI中顯示錯誤,並且可以從CanSave方法進行查詢。 – Will

+0

爲什麼壞主意?除了我無法調用CanSave方法 – mi4man

+0

這是一個壞主意,因爲您無法訪問在視圖模型中在UI中定義的驗證錯誤。 – Will

回答

2

當您遵循MVVM模式並綁定到視圖模型的命令屬性時,通常應該在視圖模型類中實現驗證邏輯,而不是使用驗證規則。

您可以通過實現IDataErrorInfo接口或.NET Framework 4.5中引入的更新,更靈活的INotifyDataErrorInfo接口來實現此目的。請參閱以下博客文章以獲取更多信息:https://blog.magnusmontin.net/2013/08/26/data-validation-in-wpf/