【问题标题】:IDataErrorInfo with the same validation for all the text boxesIDataErrorInfo 对所有文本框具有相同的验证
【发布时间】:2014-01-30 08:49:11
【问题描述】:

目前我正在使用 IDataErrorInfo 但问题是我想使用 对所有文本框进行此精确代码验证,现在如果我为 textBox1 框输入无效数据,所有 textBox2 都会出现红色边框。

我不想为所有文本框使用特定大小写(我有更多的 15 个...),因为所有文本框的验证中的所有内容都应该相同。应该怎么分?

   public string Error
        {
            get { throw new NotImplementedException(); }
        }

        public string this[string columnName]
        {
            get
            {
                var error = "";
                switch (columnName)
                {
                    case "ListItem":

                        if (ListItem != null)
                        {
                            var list = new List<String> { "FirstName", "LastName", "BusinessItem", "BusinessItems" };

                            string value = ListItem.Trim();

                            var isValid = true;
                            if (!string.IsNullOrEmpty(value))
                            {
                                isValid = list.Contains(value);
                                if (!isValid)
                                {
                                    error = "Please enter either FirstName, LastName, BusinessItem, or BusinessItems";
                                }
                            }
                        }
                        break;
                }
                return error;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

Xaml

<TextBox  name="textBox1" Text="{Binding Path=ListItem,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
              HorizontalAlignment="Center" VerticalAlignment="Center" Width="200"/>


<TextBox  name="textBox2" Text="{Binding Path=ListItem,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
              HorizontalAlignment="Center" VerticalAlignment="Center" Width="200"/>

【问题讨论】:

  • 您实际上是否将所有文本框绑定到同一个属性?

标签: c# wpf xaml mvvm


【解决方案1】:

我假设您将每个 TextBox 绑定到不同的属性。您可以使用 reflection 通过其名称访问该属性。将其分解为一个函数,您可以执行类似的操作:

private bool validateProperty(string propertyName)
{            
    string value = GetType().GetProperty(propertyName).GetValue(this, null) as string;
    if (value != null)
    {
        var list = new List<String> { "FirstName", "LastName", "BusinessItem", "BusinessItems" };

        value = value.Trim();

        if (!string.IsNullOrEmpty(value))
            return list.Contains(value);
    }

    return false;    
}

public string this[string columnName]
{
    get
    {
        // if you validate more properties, you may want to check if columnName
        // follows a pattern (eg. columnName.Contains("ListItem") )

       if (!validateProperty(columName))
          return "Please enter either FirstName, LastName, BusinessItem, or BusinessItems";

       return string.Empty;
     }
}

编辑

从您的 cmets 中,我发现我的假设是错误的,您可能对 IDataErrorInfo 验证的工作原理有些困惑,所以让我从您的绑定中解释一下:

Text="{Binding Path=ListItem, 
               UpdateSourceTrigger=PropertyChanged,
               ValidatesOnDataErrors=True}"

通过指定ValidatesOnDataErrors=True,您实际上是在绑定中添加DataErrorValidationRule。当TextBox.Text 属性更改时调用此规则,并为绑定源(DataContext.ListItem)的绑定属性调用IDataErrorInfo.Item(索引器)。

因此,每次 TextBox 中的文本更改时,规则都会调用 DataContext["ListItem"],如果它返回的内容不同于空字符串,则验证失败,更新 attached Validation properties - WPF 默认处理显示控件周围的红色矩形。

因此,只要您使用ValidatesOnDataErrors=true,您就无法通过IDataErrorInfo 执行验证,它只支持DataContext 对象中的每个属性出现一个错误。因此,

  1. 您无法知道哪个控件触发了绑定属性的验证 (ListItem)。
  2. 您只能为绑定的属性 (ListItem) 返回一个错误,并且该属性同时只有一个有效的验证错误。

如果您使用的是 .NET 4.5 或 Silverlight 4+,则可以使用INotifyErrorDataError Interface,它支持每个属性出现多个错误

【讨论】:

  • 感谢 jnovo 我已经尝试过了,但它的运行方式相同,验证被读取了两次(如果我有两个文本框并且在第一个中输入了错误的值)并且我在两个文本中都得到了相同的错误框,而我只想获得第一个文本框...
  • @JeanTehhe textBox1 绑定到属性ListItem1textBox2 绑定到ListItem2,对吗?如果您将它们绑定到相同的属性,则会应用相同的验证,因此会显示相同的错误:验证是按属性执行的,而不是按控件执行的;该控件只是反映了绑定属性的验证结果。
  • 这是我想避免的问题,因为他们需要使用确切的验证
  • @JeanTehhe 请检查编辑,看看这是否是您的方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
相关资源
最近更新 更多