WPF-ValidationRule 資料驗證

來源:互聯網
上載者:User

XAML

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="192" Width="537"
    xmlns:local="clr-namespace:WpfApplication1">

    <Window.Resources>
        <!--判斷規則-->
        <local:NumberRangeRule x:Key="numberRangeRule"></local:NumberRangeRule>
    </Window.Resources>

    <Grid Name="grid" ClipToBounds="False"  Height="129" Width="297">
        <Label HorizontalAlignment="Left" Margin="25,53,0,0" Name="label2" Width="49" Height="28" VerticalAlignment="Top">年齡:</Label>
        <!--綁定 Error Content 到ToolTip-->
        <TextBox Margin="94,50,0,56"   ToolTip="{Binding RelativeSource={RelativeSource self}, Path=(Validation.Errors)[0].ErrorContent}" 
                 Name="txtAge" HorizontalAlignment="Left" Width="101">
            <TextBox.Text>
                <!--綁定Age資料 和 判斷規則 並設定最大最小值-->
                <Binding Path="Age" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <local:NumberRangeRule Min="0" Max="128" />
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
    </Grid>
</Window>

 

 

C#

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;

using System.ComponentModel;

namespace WpfApplication1
{
    /// <summary>
    /// Window1.xaml 的互動邏輯
    /// </summary>
    public partial class Window1 : Window
    {
        public Person person;
        public Window1()
        {
            InitializeComponent();

            //建立樣本資料並綁定
            person = new Person();
            person.Name = "kill";
            person.Age = 21;
            this.txtAge.DataContext = person;
        }
    }

    //資料類要繼承INotifyPropertyChanged
    public class Person : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        int age;
        public int Age
        {
            get { return age; }
            set { age = value; }
        }

        public Person() { }   
    }

    //書寫繼承ValidationRule的判斷規則類
    //重寫Validate方法完成自己的判斷
    public class NumberRangeRule : ValidationRule
    {
        int min;
        public int Min
        {
            get { return min; }
            set { min = value; }
        }

        int max;
        public int Max
        {
            get { return max; }
            set { max = value; }
        }

        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            int number;
            if (!int.TryParse((string)value, out number))
            {
                return new ValidationResult(false, "Invalid number format");
            }

            if (number < min || number > max)
            {
                return new ValidationResult(false, string.Format("Number out of range ({0} - {1})", min, max));
            }

            return ValidationResult.ValidResult;
        }
    }

}

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.