你可以使用DataAnnotations
样本
using System.ComponentModel.DataAnnotations;
[Required] //tells your XAML that this value is required
[RegularExpression(@"^[0-9\s]{0,40}$")]// only numbers and between 0 and 40 digits allowed
public int yourIntValue
{
get { return myValue; }
set { myValue= value; }
}
好的,这里有一个 komplett 示例
XAML
<Window x:Class="DataAnnotations.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Width="100" Height="25"
Text="{Binding Path=CartPayment, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Name="txtPayment" Margin="22,20,381,266" />
</Grid>
</Window>
代码隐藏
using System.Windows;
using System.ComponentModel.DataAnnotations;
namespace DataAnnotations
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new Cl();
}
}
public class Cl
{
private decimal _cartPayment;
[Required]
[RegularExpression(@"^\d+(\.\d{1,2})?$")]
public decimal CartPayment
{
get {
return _cartPayment; }
set
{
_cartPayment = value;
}
}
}
}