【问题标题】:Silverlight Validation for TextBox bound to non-string datatype绑定到非字符串数据类型的 TextBox 的 Silverlight 验证
【发布时间】:2012-07-27 20:43:23
【问题描述】:

在我开始尝试在绑定到非字符串数据类型属性的 TextBox 上使用它之前,使用 INotifyDataErrorInfo 进行的 Silverlight 验证工作得很好。我的计划是使用属性的设置器来执行验证逻辑,并根据需要从那里添加和删除错误。它适用于作为字符串的 TextBox,但是如果您有一个绑定到 Int 的 TextBox 并且您输入了一个字符串,则设置器甚至不会被调用(我可以在其中添加一个明显非数字值的错误无效的)。从这里建议的行动方案是什么?我研究了 ValueConverters,但它们与正在验证的类中的 INotifyDataErrorInfo 逻辑相距甚远。

假设示例:

public class MyClass
{
    private string _prod;
    public string Prod
    {
        get { return _prod; }
        set //This works great
        {
            if (value.Length > 15)
            {
                AddError("Prod", "Cannot exceed 15 characters", false);
            }
            else if (value != _prod)
            {
                RemoveError("Prod", "Cannot exceed 15 characters");
                _prod= value;
            }
        }
    }

    private int _quantity;
    public int Quantity
    {
        get { return _quantity; }
        set //if a string was entered into the textbox, this setter is not called.
        {
            int test;
            if (!int.TryParse(value, test))
            {
                AddError("Quantity", "Must be numeric", false);
            }
            else if (test != _quantity)
            {
                RemoveError("Quantity", "Must be numeric");
                _quantity= test;
            }
        }
    }

    protected Dictionary<String, List<String>> errors = 
        new Dictionary<string, List<string>>();

    public void AddError(string propertyName, string error, bool isWarning)
    {
        //adds error to errors
    }
    public void RemoveError(string propertyName, string error)
    {
        //removes error from errors
    }

    //INotifyDataErrorInfo members...
}

【问题讨论】:

    标签: silverlight validation inotifydataerrorinfo


    【解决方案1】:

    我建议您将 TextBox 的值绑定到字符串值并在那里进行验证。 如果验证成功,则将值传递给具有您实际查找的数据类型(例如 int)的另一个属性。在任何其他情况下,验证失败。 只是一种解决方法......但对我有用。

    【讨论】:

    • 其实我已经在考虑这个了。唯一阻碍我的是我将有大量的输入。为所有数字属性设置一个字符串属性只会增加混乱。
    • 我将此标记为答案,因为它是一个很好的解决方法,但只是作为对任何可能与我处于相同情况且具有许多非字符串属性的人的建议:有一个 numericUpDown 控件在将文本输入限制为数值的工具包中,因此不再需要验证。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 2020-05-22
    • 2013-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多