2012-03-06 44 views
0

我想在使用MVVM的WPF應用程序中爲電話號碼字段設置驗證。我有文本框綁定,但似乎無法弄清楚拒絕輸入和彈出工具提示的邏輯。任何建議,將不勝感激。如何顯示無效輸入到文本框的工具提示

[Required] 
    public string PhoneNumber 
    { 
     get 
     { 
      return EntityPhone.PhoneNumber; 
     } 
     set 
     { 
      int intValue = 0; 
      if(!int.TryParse(value, out intValue)) 
      { 
//    ToolTip tt = new ToolTip(); 
//    tt.Content = "Invalid Character. Please enter a valid 10-digit number"; 
      } 
      EntityPhone.PhoneNumber = value; 
      NotifyOfPropertyChange(() => PhoneNumber); 
     } 
    } 
+3

閱讀:http://blogs.msdn.com/b/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx – Bolu 2012-03-06 17:26:39

回答

1

首先,你想使你的類繼承IDataErrorInfo,這是使用WPF進行驗證。

public class MyClass : IDataErrorInfo 
{ 
    ... 

    #region IDataErrorInfo Members 

    string IDataErrorInfo.Error 
    { 
     get { return null; } 
    } 

    string IDataErrorInfo.this[string columnName] 
    { 
     get 
     { 
      if (columnName == "PhoneNumber") 
      { 
       // Validate property and return a string if there is an error 
       return "Some error"; 
      } 

      // If there's no error, null gets returned 
      return null; 
     } 
    } 
    #endregion 
} 

接下來,告訴你的結合,它應該被驗證的值時,它改變

<TextBox Text="{Binding Path=PhoneNumber, ValidatesOnDataErrors=True}" ... /> 

最後,創建驗證模板。這裏的風格/模板我通常使用

<!-- ValidatingControl Style --> 
<Style TargetType="{x:Type FrameworkElement}" x:Key="ValidatingControl"> 
    <Style.Triggers> 
     <Trigger Property="Validation.HasError" Value="True"> 
      <Setter Property="ToolTip" Value="{Binding 
       Path=(Validation.Errors)[0].ErrorContent, 
       RelativeSource={x:Static RelativeSource.Self}}" /> 
     </Trigger> 
    </Style.Triggers> 
</Style>