需要驗證用戶輸入的數據類型是否爲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>