簡體   English   中英

C#WPF非常簡單的TextBox驗證

[英]C# WPF very simple TextBox Validation

我是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周圍會出現紅色邊框

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM