c# WPF非常简单的文本框验证

本文关键字:文本 验证 简单 WPF 非常 | 更新日期: 2023-09-27 18:15:27

我完全是c#初学者....我想为一个文本框创建一个非常简单的验证。下面是我到目前为止的代码:

MainWindow.xaml.cs

namespace Mynamespace
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void TextBox_TextChanged_2(object sender, TextChangedEventArgs e)
        {
        }
    }
    public class AgeValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            int wert = Convert.ToInt32(value);
            if (wert < 0)
                return new ValidationResult(false, "just positiv values allowed");
            return new ValidationResult(true, null);
        }
    }
}

MainWindow.xaml

<Window x:Class="Mynamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Mynamespace"
        Title="MainWindow"
        Height="350"
        Width="525">
<Window.Resources>
</Window.Resources>
<Grid>
    <TextBox HorizontalAlignment="Left"
             Height="23"
             TextWrapping="Wrap"
             VerticalAlignment="Top"
             Width="120"
             Margin="167,107,0,0"
             TextChanged="TextBox_TextChanged_2">
        <Binding Path="Alter"
                 UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:AgeValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox>
</Grid>

没有错误,但它不工作…我错过什么了吗?

c# WPF非常简单的文本框验证

TextBox应该绑定到属性Alter。为了使绑定工作,你需要设置DataContext -一个具有Alter属性的对象,例如

public class Test
{
    public string Alter { get; set; }
}

public MainWindow()
{
    InitializeComponent();
    DataContext = new Test();
}

如果输入负数,文本框

周围会有红色边框