私はC#の完全な初心者です... TextBoxの非常に単純な検証を作成したいと思います。これまでの私のコードは次のとおりです。
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>
エラーはありませんが、機能しません...何かが足りませんか?
TextBoxはプロパティにバインドされることになっていますAlter
。バインディングを機能させるには、DataContextを設定する必要があります-Alter
プロパティを持つオブジェクト。
public class Test
{
public string Alter { get; set; }
}
そして
public MainWindow()
{
InitializeComponent();
DataContext = new Test();
}
次に負の数を入力すると、TextBoxの周りに赤い境界線が表示されます
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加