2016-10-28 14 views
1

私はC#の初心者です。私はTextBoxの非常に簡単な検証を作成したいと思います。C#WPF非常に簡単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> 

エラーなし、それが動作しません...午前:ここに私のコードは、これまでのところです私は何かを欠いている?

+0

周りに赤い境界線があるでしょう、私はこの質問を閉じるために投票:「デバッグ助けを求める質問(」理由ではありませんこのコードは動作していますか? ")には、目的の動作、特定の問題またはエラー、およびその問題自体を再現するのに必要な最短コードが含まれていなければなりません。 、完了して、検証可能な例 " –

答えて

2

TextBoxはプロパティAlterにバインドされているはずです。バインドするには、Alterというプロパティを持つオブジェクト、例えば、DataContextを設定する必要があります。

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

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

あなたが負の数を入力すると、その後、テキストボックス

関連する問題