Reputation: 961
I have a text box in an MVVM WPF application, bound to this property:
private decimal _cartPayment;
public decimal CartPayment {
get { return _cartPayment; }
set {
_cartPayment = value;
this.NotifyPropertyChanged("CartPayment");
}
}
My question is, how do I limit the range of values allowed? For example it should only be two decimal places.
In a similar issue I have another ushort
property called Quantity
, The value should not be 0.
How do I set it so that when the user types something illegal (e.g more than 2 decimal places for the first example, and 0 for the Quantity field), the control will be surrounded by a red border like so?
Upvotes: 1
Views: 122
Reputation: 5420
you can use DataAnnotations
sample
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; }
}
ok here an komplett example
<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;
}
}
}
}
Upvotes: 1
Reputation: 1445
You can use ValidationRules
For more information : system.windows.data.binding.validationrules
Upvotes: 0
Reputation: 30097
Take a look at IDataErrorInfo interface. You can use this interface in combination with XAML to show user the validation errors on UI.
Google it you will find lot of samples and tutorials. For start take a look at Validation made easy with IDataErrorInfo
Upvotes: 1