C# WPF 非常简单的 TextBox 验证

Jak*_*zig 7 c# validation wpf xaml textbox

我是 C# 的初学者.... 我想为 TextBox 创建一个非常简单的验证。到目前为止,这是我的代码:

主窗口.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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

主窗口.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>
Run Code Online (Sandbox Code Playgroud)

没有错误,但它不起作用......我错过了什么吗?

ASh*_*ASh 6

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

public class Test
{
    public string Alter { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

public MainWindow()
{
    InitializeComponent();
    DataContext = new Test();
}
Run Code Online (Sandbox Code Playgroud)

那么如果你输入负数,TextBox周围会有红色边框