2011-08-15 30 views
4

我正在編寫驗證規則到XAML中的各種控件的過程。我想在運行時將驗證規則附加到控件,而不是在XAML中。我正在考慮使用轉換器。但任何想法/想法都是更好的方法來完成這一點。WPF在運行時Binding.ValidationRules

示例代碼:

<TextBox Name="txtFirstName" > <TextBox.Text> <Binding Path="FirstName" ValidatesOnDataErrors="True" PropertyChanged" > 
      <Binding.ValidationRules> 
       <Binding Converter="{StaticResource validationConverter}"/> 
      </Binding.ValidationRules>    
    </Binding>            


public class ValidationConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, 
     System.Globalization.CultureInfo culture) 
    { 
     Binding b = new Binding(); 
     b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; 
     b.ValidatesOnDataErrors = true; 
     b.NotifyOnValidationError = true; 
     b.ValidationRules.Add(new RangeValidationRule { ErrorMessage = "Error shown from Converter ", MinValue = 10, MaxValue = 50 }); 
     return b; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

感謝,

+0

可能有一些[MVVM框架](http://channel9.msdn.com/Events/MIX/MIX10/EX15)這將支持這一點,但我不是這方面的專家。 –

回答

2

的方法,我用的是創建有我的自定義驗證內置了不同的風格。然後,它只是在運行時分配適當的Style,其中包含所需的驗證。

編輯

下面是創建一種風格叫NumericTextBox一個基本的例子:

<Style x:Key="NumericTextBox"> 
    <Setter Property="TextBox.VerticalAlignment" 
      Value="Stretch"/> 
    <Setter Property="TextBox.VerticalContentAlignment" 
      Value="Center"/> 
    <Setter Property="TextBox.Height" 
      Value="24"/> 
    <Setter Property="TextBox.Margin" 
      Value="0,2,0,2"/> 
    <EventSetter Event="UIElement.PreviewTextInput" 
       Handler="tbx_DigitCheck"/> 
    <EventSetter Event="UIElement.PreviewKeyDown" 
       Handler="tbx_OtherCharCheck"/> 
    <EventSetter Event="UIElement.PreviewDragEnter" 
       Handler="tbx_PreviewDragEnter"/> 

</Style> 

下面的方法是把代碼隱藏文件的資源字典的方式存儲在哪裏。此方法確保只能在文本框中輸入數字和有效的小數點分隔符。每個字符在實際顯示在文本框中之前都會檢查其是否有效。

Public Sub tbx_DigitCheck(ByVal sender As Object, _ 
         ByVal e As TextCompositionEventArgs) 

    //Retireve the sender as a textbox. 
    Dim tbx As TextBox = CType(sender, TextBox) 
    Dim val As Short 

    //Get the current decimal separator. 
    Dim dSep As String = Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator 

    //Check to make sure that a decimal separator character has not 
    //already been entered in the textbox. Only make this check 
    //for areas of the text that are not selected. 
    If e.Text = dSep And tbx.SelectedText.Contains(dSep) Then 
    //Do Nothing. Allow the character to be typed. 
    ElseIf e.Text = dSep And tbx.Text.Contains(dSep) Then 
    e.Handled = True 
    End If 

    //Only allow the decimal separator and numeric digits. 
    If Not Int16.TryParse(e.Text, val) And Not e.Text = dSep Then 
    e.Handled = True 
    End If 

End Sub 
+0

感謝您的回覆..您可以請分享一個例子來實現這一點。謝謝, – 2011-08-15 16:35:18