日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > windows >内容正文

windows

WPF --- TextBox的输入校验

發布時間:2023/11/18 windows 47 coder
生活随笔 收集整理的這篇文章主要介紹了 WPF --- TextBox的输入校验 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

引言

在WPF應用程序開發中,數據校驗是確保用戶輸入數據的正確性和完整性的重要一環。

之前在做一些參數配置功能時,最是頭疼各種參數校驗,查閱一些資料后,我總結了數據校驗方式有兩種:

  • ValidationRule
  • IDataErrorInfo

接下來分別介紹這兩種校驗方式。

ValidationRule

ValidationRule 是一個抽象類,提供了抽象方法 Validate(), 它是WPF中用于數據驗證的一種機制,它可以在用戶輸入數據之前或之后執行自定義的驗證邏輯。可以輕松地實現對數據的格式、范圍、邏輯等方面的驗證,并在驗證失敗時提供相應的反饋信息。

ValidationRule主要作用域在前端頁面上

基本用法

首先創建一個 ValidationRule,我這里設定了兩個屬性 MaxValMinVal,然后在 Validate() 方法中判斷空、判斷大于上限或小于下限,然后在符合條件是,返回 ValidationResult,并給出錯誤提示:

public class IntegerValidationRule : ValidationRule
{
    public int MaxVal { get; set; }
    public int MinVal { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        string text = value as string;

        if (!int.TryParse(text, out int result))
        {
            return new ValidationResult(false, "Text cannot be empty.");
        }

        if (result > MaxVal)
        {
            return new ValidationResult(false, "Value out of upper limit range.");
        }

        if (result < MinVal)
        {
            return new ValidationResult(false, "Value out of lower limit range.");
        }

        return ValidationResult.ValidResult;
    }
}

接下來創建有個測試使用的 ViewModel:

public class TestViewModel : INotifyPropertyChanged
{
    private TestViewModel() { }

    public static TestViewModel Instance { get; } = new TestViewModel();

    public event PropertyChangedEventHandler? PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private int testField1;
    /// <summary>
    /// 測試屬性1
    /// </summary>
    public int TestField1
    {
        get => testField1;
        set
        {
            testField1 = value;
            OnPropertyChanged(nameof(TestField1));
        }
    }

    private int testField2;
    /// <summary>
    /// 測試屬性2
    /// </summary>
    public int TestField2
    {
        get => testField2;
        set
        {
            testField2 = value;
            OnPropertyChanged(nameof(TestField2));
        }
    }
}


在測試之前,我們可以先看一下 Binding 的方法列表:

可以看到 ValidationRulesBinding 下的集合,這意味著 ValidationRule 是在 Binding 下使用且可以執行多個校驗規則。校驗時按照順序依次校驗。

接下來我們創建一個WPF應用程序,在界面添加 TextBox,命名為”textbox1“,將文本綁定在 TestViewModelTestField1

且為Validation.ErrorTemplate 綁定一個模板,這里綁定了一個紅色的感嘆號。

然后為 TextBox 設置觸發器,當 Validation.HasErrortrue時,將 ToolTip 綁定校驗失敗的錯誤提示。

代碼如下:

<Window
    x:Class="WpfApp4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:WpfApp4"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="MainWindow"
    Width="900"
    Height="450"
    mc:Ignorable="d">
    <Window.Resources>
        <ControlTemplate x:Key="ValidationTemplate">
            <DockPanel>
                <TextBlock
                    Margin="-10,0,0,0"
                    VerticalAlignment="Center"
                    FontSize="22"
                    Foreground="Red"
                    Text="!" />

            </DockPanel>
        </ControlTemplate>

        <Style TargetType="TextBox">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="1*" />
        </Grid.ColumnDefinitions>
        <StackPanel Grid.Column="0">
            <TextBlock
                HorizontalAlignment="Center"
                FontSize="18"
                FontWeight="Bold"
                Text="Validation Demo" />
            <TextBox
                Name="textBox1"
                Height="30"
                Margin="10"
                FontSize="22"
                Validation.ErrorTemplate="{StaticResource ValidationTemplate}">
                <TextBox.Text>
                    <Binding Path="TestField1" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                            <local:IntegerValidationRule
                                MaxVal="999"
                                MinVal="5" />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>

        </StackPanel>
    </Grid>
</Window>

最后在窗體后臺綁定 ViewModel:

public MainWindow()
{
    InitializeComponent();
    this.DataContext =  TestViewModel.Instance;
}

測試

  1. 為空時,出現紅色嘆號,ToolTip 提示 "Text cannot be empty."

  2. 小于下限時,出現紅色嘆號,ToolTip 提示 "Value out of lower limit range."

  3. 大于上限時,出現紅色嘆號,ToolTip 提示 "Value out of upper limit range."

IDataErrorInfo

IDataErrorInfo 是一個接口,Viewmodel 實現接口用于在后臺,提供數據驗證和錯誤信息。

IDataErrorInfo 主要作用域為后臺 ViewModel
該接口包含兩個成員:Errorthis[string columnName]。這兩個成員允許你在數據綁定時提供驗證錯誤信息。

基本用法

接下來,在程序里添加 TextBox,命名為”textbox2“,并添加一個 TextBlock 綁定 Error 展示在界面。

<StackPanel Grid.Column="1">
    <TextBlock
        HorizontalAlignment="Center"
        FontSize="18"
        FontWeight="Bold"
        Text="IDataErrorInfo Demo" />
    <TextBox
        Name="textBox2"
        Margin="10"
        VerticalAlignment="Center"
        FontSize="22"
        Text="{Binding TestField2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
     <TextBlock
         HorizontalAlignment="Center"
         FontSize="18"
         FontWeight="Bold"
         Foreground="Red"
         Text="{Binding Error, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>

后臺 TestViweModel 實現 IDataErrorInfo,依舊是判斷上限值和下限值,此處不判斷空,是因為后臺 TestField2 類型是Int,為空時不會賦值,代碼如下:

public class TestViewModel : INotifyPropertyChanged, IDataErrorInfo
{
    //省略上文已有代碼..。
    
    private string error;
    public string Error
    {
        get => error;
        set
        {
            error = value; OnPropertyChanged(nameof(Error));
        }
    }
    public string this[string columnName]
    {
        get
        {
            switch (columnName)
            {
                case nameof(TestField2):
                    return CheckTestFild2();
                default:
                    return null;
            }
        }
    }

    public int MaxVal = 999;
    public int MinVal = 5;

    private string CheckTestFild2()
    {
        if (TestField2 > MaxVal)
        {
            Error = "Value out of upper limit range in viewmodel.";
        }
        else if (TestField2 < MinVal)
        {
            Error = "Value out of lower limit range  in viewmodel.";
        }
        else
        {
            Error = string.Empty;
        }
        
        return Error;
    }
}

測試

  1. 小于下限時,出現紅色文字提示,ToolTip 提示 "Value out of lower limit range in viewmodel."

  2. 大于上限時,出現紅色文字提示,ToolTip 提示 "Value out of upper limit range in viewmodel."

小結

以上兩種數據校驗(IDataErrorInfoValidationRule)的方式,均可以實現自定義數據校驗,例如對數據的格式、范圍、邏輯等方面的驗證,并在驗證失敗時提供相應的反饋信息。

ValidationRule適用于在界面做數據校驗,且可以定義多個校驗規則。

ValidationRule適用于在ViewModel做數據校驗,可以做一些無法在前端頁面做的事情,比如出現異常值是還原為默認值。

所以兩者既可以單獨使用,也可以組合使用,即使使用MVVM模式,依舊能夠優雅的做數據校驗。

總結

以上是生活随笔為你收集整理的WPF --- TextBox的输入校验的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。