2011-06-21 61 views
1

我有一個工作的WPF對話框使用DataGrid。 DataGrid設置爲ItemsSource={Binding SomeCollection, Mode=TwoWay}。這個設置工作正常,我可以讀取值並從UI更新它們。

稍後我添加了轉換器來驗證值。驗證失敗時,我顯示空白。如果驗證失敗,現在我有興趣返回原始值。

我如何獲得原始值,如果我的數據綁定失敗驗證

我在這裏有什麼選擇?

回答

6

我從來沒有使用轉換器進行驗證。相反,我使用的是實現IDataErrorInfo的項目,其中的數據綁定屬性中的屬性爲ValidatesOnDataErrors = True。

使用這種驗證方法,原始值被保留,對象返回錯誤值(在我的情況下是一個字符串,說明錯誤是什麼)。我的視圖的控件有一個自定義驗證項目,它添加了隨着時間推移而漸漸消失的紅色邊框以及在鼠標懸停時彈出的工具提示。

接下來,你需要把你的驗證規則中的數據類正在顯示:

Private Sub OnAddress1Changed() 
    Me.RemoveError("Address1") 
    If _Address1 Is Nothing OrElse _Address1.Trim = "" Then 
     Me.AddError("Address1", "Please enter a valid Address Line") 
    End If 
    OnPropertyChanged("CanShip") 
End Sub 


Private m_validationErrors As New Dictionary(Of String, String) 
Private Sub AddError(ByVal ColName As String, ByVal Msg As String) 
    If Not m_validationErrors.ContainsKey(ColName) Then 
     m_validationErrors.Add(ColName, Msg) 
    End If 
End Sub 
Private Sub RemoveError(ByVal ColName As String) 
    If m_validationErrors.ContainsKey(ColName) Then 
     m_validationErrors.Remove(ColName) 
    End If 
End Sub 


Public ReadOnly Property [Error]() As String Implements System.ComponentModel.IDataErrorInfo.Error 
    Get 
     If m_validationErrors.Count > 0 Then 
      Return "Shipment data is invalid" 
     Else 
      Return Nothing 
     End If 
    End Get 
End Property 

Default Public ReadOnly Property Item(ByVal columnName As String) As String Implements System.ComponentModel.IDataErrorInfo.Item 
    Get 
     If m_validationErrors.ContainsKey(columnName) Then 
      Return m_validationErrors(columnName).ToString 
     Else 
      Return Nothing 
     End If 
    End Get 
End Property 

編輯

而只是它的心裏很不舒服,我會放一個例子驗證模板中向別人展示如何把它連接起來。

<Style x:Key="ToolTipValidation" TargetType="{x:Type Control}"> 
           <Setter Property="Validation.ErrorTemplate"> 
             <Setter.Value> 
               <ControlTemplate> 
                 <Border BorderBrush="Red" BorderThickness="2,1,2,1"> 
                   <AdornedElementPlaceholder/> 
                 </Border> 
               </ControlTemplate> 
             </Setter.Value> 
           </Setter> 
           <Style.Triggers> 
             <Trigger Property="Validation.HasError" Value="True"> 
               <Setter Property="ToolTip" Value="{Binding (Validation.Errors)[0].ErrorContent, RelativeSource={x:Static RelativeSource.Self}}"/> 
             </Trigger> 
           </Style.Triggers> 
         </Style> 

最後: A MSDN article on implementing Validation

A video to go with it.視頻數4

+0

+1一個真棒的方式來做到這一點。 我已經將我的應用程序更新爲MVVM,並在將VM提交給實際數據之前在VM中添加了驗證邏輯。 – vrrathod

+0

您也可以查看windowsclient.net(另一個致力於WinForms和WPF開發的微軟站點)。感謝您的支持和答覆! – CodeWarrior

相關問題