PaulS PaulS - 1 month ago 5
C# Question

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?

ASh ASh
Answer

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

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

Comments