C# WPF 非常简单的文本框验证

标签 c# wpf validation xaml textbox

我是 C# 的初学者....我想为文本框创建一个非常简单的验证。到目前为止,这是我的代码:

主窗口.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);
        }
    }
}

主窗口.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 应该绑定(bind)到属性 Alter。为了绑定(bind)工作,您需要设置 DataContext - 一个具有 Alter 属性的对象,例如

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

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

那么如果你输入负数,TextBox周围会有红色边框

关于C# WPF 非常简单的文本框验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40304055/

相关文章:

asp.net - 在 asp.net 中,我需要向文本框添加验证器,强制输入为数字

c# - Lambda 表达式仅从集合中选择某些项目

C# CefSharp 离屏鼠标事件、键盘事件模拟示例

wpf - 'AllowSpin' 属性已被 'Xceed_Wpf_Toolkit_Primitives_UpDownBase' 注册

c# - 如何将控件绑定(bind)到DataGrid中的当前行?

c# - 类似于 SQL Server Management Studio 的 WinForms DataGridView 行为

python - 根据模式 python 验证 csv

c# - 如何删除对象?

c# - 尝试使用 su 执行命令时出现 SyncFailedException

wpf - Windows 10 上的空白 WPF 子窗口