using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WpfApp02
{
/// <summary>
/// TestWin05.xaml 的交互逻辑
/// </summary>
public partial class TestWin05 : Window
{
public TestWin05()
{
InitializeComponent();
Binding b = new Binding("Value"){ Source=slider};
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
b.ValidationRules.Add(new RangeValidationRule());
b.NotifyOnValidationError = true;
txt.SetBinding(TextBox.TextProperty, b);
txt.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(this.ValidationError));
}
private void ValidationError(object sender, RoutedEventArgs e)
{
if (Validation.GetErrors(txt).Count>0)
{
txt.ToolTip = Validation.GetErrors(txt)[0].ErrorContent.ToString();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace WpfApp02
{
public class RangeValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
double d = 0;
if (double.TryParse(value.ToString(),out d))
{
if (d>=0 && d<=100)
{
return new ValidationResult(true, null);
}
}
return new ValidationResult(false, "Validation failed");
}
}
}