简体   繁体   English

C#WPF非常简单的TextBox验证

[英]C# WPF very simple TextBox Validation

i'm a total Beginner at C#.... I'd like to create a very simple Validation for a TextBox. 我是C#的初学者....我想为TextBox创建一个非常简单的验证。 Here is my Code so far: 这是我的代码到目前为止:

MainWindow.xaml.cs 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 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>

no errors, but it doesn't work... am i missing something? 没有错误,但它不起作用...我错过了什么?

TextBox is supposed to be bound to property Alter . TextBox应该绑定到属性Alter For binding to work you need to set DataContext - an object with Alter property, eg 要绑定到工作,您需要设置DataContext - 具有Alter属性的对象,例如

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

and

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

then if you enter negative number, there will be red border around TextBox 然后,如果输入负数,TextBox周围会出现红色边框

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM