2016-11-29 90 views
2

需要驗證用戶輸入的數據類型是否爲int,但我不知道該怎麼做!如何獲取驗證(xaml和C#)文本框的int值?

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows; 

namespace Projekat.Validation 
{ 
    public partial class ValidationExample : Window, INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 

     protected virtual void OnPropertyChanged(string name) 
     { 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs(name)); 
      } 
     } 

     private int _test1; 

     public int Test1 
     { 
      get 
      { 
       return _test1; 
      } 
      set 
      { 
       if (value != _test1) 
       { 
        _test1 = value; 
        OnPropertyChanged("Test1"); 
       } 
      } 
     } 

     public ValidationExample() 
     { 
      //InitializeComponent(); 
      //this.DataContext = this; 
     } 

    } 
} 

和文本框的XAML

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Controls; 

namespace Projekat.Validation 
{ 
    public class StringToIntValidationRule:ValidationRule 
    { 
     public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) 
     { 
      try 
      { 
       var s = value as string; 
       int r; 
       if (int.TryParse(s, out r)) 
       { 
        return new ValidationResult(true, null); 
       } 
       return new ValidationResult(false, "Please enter a valid int value."); 
      } 
      catch 
      { 
       return new ValidationResult(false, "Unknown error occured."); 
      } 
     } 
    } 
} 

及部分

<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="145,40,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"> 
    <TextBox.Text> 
     <Binding Path="Test1" UpdateSourceTrigger="PropertyChanged"> 
      <Binding.ValidationRules> 
       <val:StringToIntValidationRule ValidationStep="RawProposedValue"/> 
      </Binding.ValidationRules> 
     </Binding> 
    </TextBox.Text> 
    <Validation.ErrorTemplate> 
     <ControlTemplate> 
      <Grid> 
       <Grid.RowDefinitions> 
        <RowDefinition /> 
       </Grid.RowDefinitions> 
       <Grid.ColumnDefinitions> 
        <ColumnDefinition /> 
        <ColumnDefinition Width="Auto" /> 
       </Grid.ColumnDefinitions> 

       <AdornedElementPlaceholder Grid.Column="0" Grid.Row="0" x:Name="textBox"/> 
       <TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding [0].ErrorContent}" Foreground="Red"/> 
      </Grid> 
     </ControlTemplate> 
    </Validation.ErrorTemplate> 
</TextBox> 

回答

1

你的代碼是OK,我發現唯一的問題是,物業Test1可能永遠不會因爲不正確設置DataContext中的綁定。看來,Test1的屬於窗口,所以我想給這個窗口在XAML名稱:

<Window x:Name="win".../> 

在這之後你只需要添加的DataContext到一個文本框:

<TextBox DataContext="{Binding ElementName=win}" .../>