我在MVVM WPF应用程序中有一个绑定到此属性的文本框:
private decimal _cartPayment;
public decimal CartPayment {
get { return _cartPayment; }
set {
_cartPayment = value;
this.NotifyPropertyChanged("CartPayment");
}
}
我的问题是,如何限制允许的值范围?例如,它应该只有两位小数。
在类似问题中,我有另一个名为ushort
的{{1}}属性,该值不应为0.
如何设置它以便当用户输入非法内容时(例如,第一个示例超过2个小数位,而“数量”字段为0),控件将被红色边框包围,如此?
答案 0 :(得分:1)
查看IDataErrorInfo界面。您可以将此界面与XAML结合使用,向用户显示UI上的验证错误。
谷歌你会发现很多样本和教程。首先,请查看Validation made easy with IDataErrorInfo
答案 1 :(得分:1)
您可以使用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例子
<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;
}
}
}
}
答案 2 :(得分:0)
您可以使用ValidationRules