简体   繁体   中英

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. Here is my Code so far:

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>

no errors, but it doesn't work... am i missing something?

TextBox is supposed to be bound to property Alter . For binding to work you need to set DataContext - an object with Alter property, eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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