在 WPF PropertyGrid 中实现验证

发布于 2024-10-07 06:01:01 字数 309 浏览 4 评论 0原文

我已经实现了一个PropertyGrid,并且所选对象(在另一个库中)的属性显示在其中。属性值通过绑定绑定到 PropertyGrid 控件。现在,我想对用户在 PropertyGrid 控件(主要是 TextBox)中输入的值执行验证,并在值不正确时向用户显示一条消息。

会有一些常见的验证,如数值、必填字段等,以及一些与业务逻辑相关的验证(如值不能大于此等)。

有哪些方法可以实现此目的(IDataErrorInfo 或其他)?

I have implemented a PropertyGrid and properties of selected object(in another library) are displayed in it. Property values are bound to PropertyGrid controls through binding. Now, I want to perform validation on values user enters in PropertyGrid control(mainly TextBox) and display a message to user if value is not correct.

There will be some common validations like numeric values, required field etc and some business logic related validations(like value can't be more then this etc.).

What all approaches are available to implement this(IDataErrorInfo or something else)?

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

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

发布评论

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

评论(3

梦罢 2024-10-14 06:01:02

如果您已经在 ViewModel 上实现了 IDataErrorInfo,我发现此数据模板对于显示错误非常有用:

<Style TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="true">
            <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
        </Trigger>
    </Style.Triggers>
</Style>

这样,您只需将 ValidatesOnDataErrors=True 设置为您的文本框绑定,如果有任何问题,您会收到一个显示错误的工具提示。这也可以应用于其他控件。

有关如何正确实现 IDataErrorInfo 的信息,请参见此处:
http://blogs .msdn.com/b/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx
特别是看看“3.5 IDataErrorInfo Support”部分

If you already have implemented IDataErrorInfo on your ViewModels, I found this data-template to be quite useful for displaying errors:

<Style TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="true">
            <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
        </Trigger>
    </Style.Triggers>
</Style>

That way, you only have to set ValidatesOnDataErrors=True on your textbox bindings and you get a tooltip displaying the error if anything is wrong. That can be applied to other controls as well.

For information on how to implement IDataErrorInfo properly, look here:
http://blogs.msdn.com/b/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx
especially have a look at the section "3.5 IDataErrorInfo Support"

鹿! 2024-10-14 06:01:02

我最近不得不处理这个问题,所以我将发布这个示例代码来帮助其他人解决同样的问题。

using System.Collections.Generic;
using System.ComponentModel;
using System.Text;

namespace ValidationExample
{

    public class SomeClass : DataErrorInfoImpl
    {
        [CustomValidation(typeof (SomeClassValidator), "ValidateSomeTextToValidate")]
        string SomeTextToValidate {get;set;}

    }

    public class SomeClassValidator
    {
        public static ValidationResult ValidateNumberOfLevelDivisons(string text)
        {
            if (text != "What every condition i want") return new ValidationResult("Text did not meet my condition.");
            return ValidationResult.Success;
        }

    }

    public class DataErrorInfoImpl : IDataErrorInfo
    {
        string IDataErrorInfo.Error { get { return string.Empty; } }

        string IDataErrorInfo.this[string columnName]
        {
            get
            {
                var pi = GetType().GetProperty(columnName);
                var value = pi.GetValue(this, null);

                var context = new ValidationContext(this, null, null) { MemberName = columnName };
                var validationResults = new List<ValidationResult>();
                if (!Validator.TryValidateProperty(value, context, validationResults))
                {
                    var sb = new StringBuilder();
                    foreach (var vr in validationResults)
                    {
                        sb.AppendLine(vr.ErrorMessage);
                    }
                    return sb.ToString().Trim();
                }
                return null;
            }
        }
    }
}

此样式应适用于 WPF Xceed.PropertyGrid 和 WPF PropertyTools.PropertyGrid。

I recently had to deal with this problem so I will post this example code to help others with the same problem.

using System.Collections.Generic;
using System.ComponentModel;
using System.Text;

namespace ValidationExample
{

    public class SomeClass : DataErrorInfoImpl
    {
        [CustomValidation(typeof (SomeClassValidator), "ValidateSomeTextToValidate")]
        string SomeTextToValidate {get;set;}

    }

    public class SomeClassValidator
    {
        public static ValidationResult ValidateNumberOfLevelDivisons(string text)
        {
            if (text != "What every condition i want") return new ValidationResult("Text did not meet my condition.");
            return ValidationResult.Success;
        }

    }

    public class DataErrorInfoImpl : IDataErrorInfo
    {
        string IDataErrorInfo.Error { get { return string.Empty; } }

        string IDataErrorInfo.this[string columnName]
        {
            get
            {
                var pi = GetType().GetProperty(columnName);
                var value = pi.GetValue(this, null);

                var context = new ValidationContext(this, null, null) { MemberName = columnName };
                var validationResults = new List<ValidationResult>();
                if (!Validator.TryValidateProperty(value, context, validationResults))
                {
                    var sb = new StringBuilder();
                    foreach (var vr in validationResults)
                    {
                        sb.AppendLine(vr.ErrorMessage);
                    }
                    return sb.ToString().Trim();
                }
                return null;
            }
        }
    }
}

This style should work on WPF Xceed.PropertyGrid and WPF PropertyTools.PropertyGrid.

じ违心 2024-10-14 06:01:02

我建议使用IDataErrorInfo。这样,验证逻辑将保持附加到 ViewModel 而不是 UIWPF 也对其提供了很好的支持。

I recommend using IDataErrorInfo. That way, validation logic stays attached to ViewModel and not the UI. And WPF has well support for it as well.

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