WPF( 数据验证)

作者:金牛区福生殡葬服务部 来源:www.cdfsbz.com 发布时间:2018-04-07 09:42:49
WPF( 数据验证)

[html]
<Window x:Class="TestOfValidationRules.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">
<StackPanel >
<TextBox x:Name="textBox1" Margin="5" />
<Slider x:Name="slider1" Minimum="-10" Maximum="110" Margin="5" />

</StackPanel>
</Window>

<Window x:Class="TestOfValidationRules.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">
<StackPanel >
<TextBox x:Name="textBox1" Margin="5" />
<Slider x:Name="slider1" Minimum="-10" Maximum="110" Margin="5" />

</StackPanel>
</Window>
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Navigation;
using System.Windows.Shapes;

namespace TestOfValidationRules
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

Binding binding = new Binding("Value")
{
Source = this.slider1
};

binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

RangeValidateRule rvr = new RangeValidateRule();
rvr.ValidatesOnTargetUpdated = true;
binding.ValidationRules.Add(rvr);

binding.NotifyOnValidationError = true;
this.textBox1.SetBinding(TextBox.TextProperty, binding);
this.textBox1.AddHandler(Validation.ErrorEvent,new RoutedEventHandler(this.ValidationError));
}

void ValidationError(object sender, RoutedEventArgs e)
{
if (Validation.GetErrors(this.textBox1).Count > 0)
{
this.textBox1.ToolTip = Validation.GetErrors(this.textBox1)[0].ErrorContent.ToString();
}
}


}

public class RangeValidateRule:ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.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 !!!");
}
}
}

企业建站2800元起,携手武汉肥猫科技,做一个有见地的颜值派!更多优惠请戳:汉阳网站建设 http://www.Hywzjs.cn

  • 上一篇:[Android-006][对话框]
  • 下一篇:最后一页
  • 
    COPYRIGHT © 2015 金牛区福生殡葬服务部 ALL RIGHTS RESERVED.
    购买cdfsbz.com友情链接、项目合作请联系客服QQ:2500-38-100 邮箱:2500-38-100#QQ.com(#换@)
    本站所有原创信息,未经许可请勿任意转载或复制使用 网站地图 技术支持:肥猫科技
    精彩专题:网站建设
    购买本站友情链接、项目合作请联系客服QQ:2500-38-100