文本框验证问题

发布于 2024-12-04 23:14:49 字数 4443 浏览 0 评论 0原文

我正在尝试获取一个文本框以在 WPF 中进行验证。问题是,当文本框中没有输入任何数据时,会导致验证错误,但不会显示验证错误。有人可以给我一些帮助吗?先感谢您。这是我的代码

public class User
    {
        private string _name;

        public string myName
        {
            get { return _name; }
            set
            {
                _name = value;
                if (String.IsNullOrEmpty(value))
                {
                    throw new ApplicationException("User name is mandatory.");
                }
            }
        }
    }
<TextBox Height="23"
                 HorizontalAlignment="Right"
                 Margin="0,0,194,250" Name="textBox1"
                 VerticalAlignment="Bottom"
                 Width="120" >
                <TextBox.Text>
                    <Binding Path="myName" >
                        <Binding.ValidationRules>
                            <ExceptionValidationRule />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
        </TextBox>

编辑:我确实遇到了绑定问题。我修复了我的代码,如下: 我首先创建一个用户和一个错误模板:

<local:User x:Key="myDataSource" myName="Enter Name" />

        <ControlTemplate x:Key="validationTemplate">
            <DockPanel>
                <TextBlock Foreground="Red" FontSize="20">!!!</TextBlock>
                <AdornedElementPlaceholder/>
            </DockPanel>
        </ControlTemplate>

然后,如果存在验证错误,我会禁用保存按钮

<Button Content="Write Kml"
                Height="23"
                HorizontalAlignment="Right"
                Margin="0,0,12,41"
                Name="writeKml"
                VerticalAlignment="Bottom"
                Width="75" Click="button2_Click" >
            <Button.Style>
                <Style TargetType="{x:Type Button}">
                    <Setter Property="IsEnabled" Value="false" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ElementName=textBox1, Path=(Validation.HasError)}" Value="false">
                            <Setter Property="IsEnabled" Value="true" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>

然后我修复了文本框以允许进行正确的验证,

<TextBox Height="23"
                 HorizontalAlignment="Right"
                 Margin="0,0,194,250"
                 Name="textBox1"
                 VerticalAlignment="Bottom"
                 Validation.ErrorTemplate="{StaticResource validationTemplate}"
                 Width="120" >
                <TextBox.Text>
                    <Binding
                        Source="{StaticResource myDataSource}"
                        Path="myName"
                        UpdateSourceTrigger="PropertyChanged"
                        ValidatesOnExceptions="True"
                        ValidatesOnDataErrors="True" >
                        <Binding.ValidationRules>
                            <local:CheckName />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
        </TextBox>

这是后面的代码

public class User
    {
        private string _name;

        public string myName
        {
            get { return _name; }
            set { _name = value; }
        }
    }

    public class CheckName : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (value == null || object.Equals(value, string.Empty))
            {
                return new ValidationResult(false, "Please enter user name");
            }

            if (value.ToString() == "Enter Name")
            {
                return new ValidationResult(false, "Please enter user name");
            }

            return new ValidationResult(true, null);
        }
    }

最后我将代码添加到窗口加载例程以强制验证

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            textBox1.GetBindingExpression(TextBox.TextProperty).UpdateSource();
        }

我希望这可以帮助任何尝试在 WPF 中验证文本框的人。

I am trying to get a textbox to validate in WPF. The problem is when there is no data entered into the textbox which should cause a validation error, no validataion error shows. Can someone give me some help? Thank you in advance. Here is my code

public class User
    {
        private string _name;

        public string myName
        {
            get { return _name; }
            set
            {
                _name = value;
                if (String.IsNullOrEmpty(value))
                {
                    throw new ApplicationException("User name is mandatory.");
                }
            }
        }
    }
<TextBox Height="23"
                 HorizontalAlignment="Right"
                 Margin="0,0,194,250" Name="textBox1"
                 VerticalAlignment="Bottom"
                 Width="120" >
                <TextBox.Text>
                    <Binding Path="myName" >
                        <Binding.ValidationRules>
                            <ExceptionValidationRule />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
        </TextBox>

Edit: I really was having a problem with binding. I fixed my code, here it is:
I started with creating a user, and an error template:

<local:User x:Key="myDataSource" myName="Enter Name" />

        <ControlTemplate x:Key="validationTemplate">
            <DockPanel>
                <TextBlock Foreground="Red" FontSize="20">!!!</TextBlock>
                <AdornedElementPlaceholder/>
            </DockPanel>
        </ControlTemplate>

I then had the save button disabled if there were validation errors

<Button Content="Write Kml"
                Height="23"
                HorizontalAlignment="Right"
                Margin="0,0,12,41"
                Name="writeKml"
                VerticalAlignment="Bottom"
                Width="75" Click="button2_Click" >
            <Button.Style>
                <Style TargetType="{x:Type Button}">
                    <Setter Property="IsEnabled" Value="false" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ElementName=textBox1, Path=(Validation.HasError)}" Value="false">
                            <Setter Property="IsEnabled" Value="true" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>

Then I fixed the textBox to allow for proper validation

<TextBox Height="23"
                 HorizontalAlignment="Right"
                 Margin="0,0,194,250"
                 Name="textBox1"
                 VerticalAlignment="Bottom"
                 Validation.ErrorTemplate="{StaticResource validationTemplate}"
                 Width="120" >
                <TextBox.Text>
                    <Binding
                        Source="{StaticResource myDataSource}"
                        Path="myName"
                        UpdateSourceTrigger="PropertyChanged"
                        ValidatesOnExceptions="True"
                        ValidatesOnDataErrors="True" >
                        <Binding.ValidationRules>
                            <local:CheckName />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
        </TextBox>

here is the code behind

public class User
    {
        private string _name;

        public string myName
        {
            get { return _name; }
            set { _name = value; }
        }
    }

    public class CheckName : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (value == null || object.Equals(value, string.Empty))
            {
                return new ValidationResult(false, "Please enter user name");
            }

            if (value.ToString() == "Enter Name")
            {
                return new ValidationResult(false, "Please enter user name");
            }

            return new ValidationResult(true, null);
        }
    }

finally I added code to the window loaded routine to force validation

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            textBox1.GetBindingExpression(TextBox.TextProperty).UpdateSource();
        }

I hope this helps anyone who is trying to do validation of a textbox in WPF.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不乱于心 2024-12-11 23:14:49

您的 User 类需要实现 INotifyPropertyChanged 才能支持 WPF 中的数据绑定。您可能需要阅读一些有关 WPF 和数据绑定的内容,因为这是构建 WPF(或 Silverlight)应用程序所需的基础知识。

几个入门链接:

数据绑定概述

INotifyPropertyChanged 接口

Your User class needs to implement INotifyPropertyChanged in order for it to support databinding in WPF. You will likely need to do a bit of reading on WPF and databinding, as it is fundamental knowledge needed to be able to build WPF (or Silverlight) applications.

Couple links to get you started:

Data Binding Overview

INotifyPropertyChanged Interface

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文