c# - 是否可以创建通用的 ValidationRule 类?

标签 c# .net wpf validation

我正在处理一个处理特定数据类型范围验证的 .NET 4.0 项目。例如,一个 32 位的 int 应该只在 Int32.MinValue 之间。和 Int32.MaxValue或应用程序定义的任何其他值。我希望能够在自定义验证器上指定数据类型和范围,以便可以通过绑定(bind)直接从 xaml 调用它们:<CheckIfValueRangeValidator>

这就是我的想法,我不确定它是否有效,或者是否可以通过 xaml 完成。

class CheckIfValueInRangeValidator<T> : ValidationRule
{
    public T Max { get; set; }
    public T Min { get; set; }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        // Implementation...
    }
}

最佳答案

糟糕,实际上你不能使用 x:TypeArguments 因为它会引发 x:TypeArguments is not allowed in object elements for XAML version than 2009, it's valid only on loose XAML files or the root元素(在我的例子中是窗口)...

http://msdn.microsoft.com/en-us/library/ms750476.aspx

但作为解决方法,您可以使用以下模式:

    <TextBox x:Name="textBox1">
        <Binding Path="MyValue"
                     Source="{StaticResource MyObject}"
                     UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <wpfApplication6:MyValidationRule ObjectType="{x:Type system:Int32}"   />
            </Binding.ValidationRules>
        </Binding>
    </TextBox>

代码隐藏:

public class MyObject
{
    public object MyValue { get; set; }
}

public class MyValidationRule : ValidationRule
{
    public Type ObjectType { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        throw new NotImplementedException();
    }
}

也看看这个: Using a Generic IValueConverter from XAML

@Blam 评论值得考虑,要检查的范围通常适用于整数或 double ,对于其他类型我会说你可以只添加一个返回该对象有效性的 bool 值并在对象本身。

对于数字,您有 RangeAttribute但它实际上并不是 WPF 验证基础结构的一部分。

您还有另一个验证选项:INotifyDataErrorInfo在这种情况下,验证发生在对象内部。

我在这里写了一个冗长的答案:https://softwareengineering.stackexchange.com/questions/203590/is-there-an-effective-way-for-creating-complex-forms您可能会在上面找到有用的东西。

根据我的经验,我认为通用验证规则可能并不明智。

您应该将您的问题编辑得不那么笼统 ;-) 而是更具体一些,您会从这里的人那里得到更多帮助。给出您要验证的对象的一两个具体案例。

编辑

您还可以使用 BindingGroup 来验证对象:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void TextBox1_OnTextChanged(object sender, TextChangedEventArgs e)
    {
        grid.BindingGroup.CommitEdit();
    }
}

public class Indices
{
    public int ColorIndex { get; set; }
    public string ColorPrefix { get; set; }
    public int GradientIndex { get; set; }
    public string GradientPrefix { get; set; }
}

public class ValidateMe : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        var bindingGroup = value as BindingGroup;
        var o = bindingGroup.Items[0] as Indices;
        return new ValidationResult(true, null);
    }
}
<Window x:Class="WpfApplication6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wpfApplication6="clr-namespace:WpfApplication6"
        Title="MainWindow"
        Width="525"
        Height="350">
    <Window.Resources>
        <wpfApplication6:Indices x:Key="Indices"
                                 ColorIndex="1"
                                 ColorPrefix="MyColor"
                                 GradientIndex="1"
                                 GradientPrefix="MyGradient" />
    </Window.Resources>
    <Grid x:Name="grid" DataContext="{StaticResource Indices}">
        <Grid.BindingGroup>
            <BindingGroup>
                <BindingGroup.ValidationRules>
                    <wpfApplication6:ValidateMe />
                </BindingGroup.ValidationRules>
            </BindingGroup>
        </Grid.BindingGroup>
        <TextBox TextChanged="TextBox1_OnTextChanged">
            <Binding Path="ColorIndex" UpdateSourceTrigger="PropertyChanged" />
        </TextBox>
    </Grid>
</Window>

使用范围属性:

    private void test()
    {
        Indices indices = new Indices();
        indices.ColorIndex = 20;

        var validationContext = new ValidationContext(indices);
        var validationResults = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
        var tryValidateObject = Validator.TryValidateObject(indices, validationContext, validationResults,true);
    }

public class Indices
{
    [Range(1, 10)]
    public int ColorIndex { get; set; }

    public string ColorPrefix { get; set; }
    public int GradientIndex { get; set; }
    public string GradientPrefix { get; set; }
}

关于c# - 是否可以创建通用的 ValidationRule 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17557068/

相关文章:

c# - 从 Java 迁移到 C#

C# Winform 按名称动态加载用户控件

TabControl 中的 C# 选项卡切换

c# - 项目管理: Implementing custom errors in VS compilation process

c# - 我如何告诉编译器忽略堆栈跟踪中的方法?

c# - 更改 DataGrid Cell WPF 关于范围的颜色

wpf - 在 DataGrid ItemsSource 更改后保持 Focus/SelectedItem

c# - 如何处理动态放置标签的重叠

c# - 首先使用实体​​框架代码实现通用存储库

c# - 为什么从 C# 应用程序代码调用 Powershell 时返回 null?