【问题标题】:MVVM-Light: Is this the best way to validate and revert a value in the View?MVVM-Light:这是在视图中验证和还原值的最佳方式吗?
【发布时间】:2011-02-12 20:53:29
【问题描述】:

在我看来,我有这样的文本框:

<TextBox x:Name="tBoxShippingWeight" Text="{Binding ShippingWeight, Mode=TwoWay}" InputScope="Number" />

当用户输入一个值时,我会进行基本验证(不是这个问题的重点),如果失败,我会使用 System.Windows.MessageBox 通知用户正确的参数并将值恢复为以前的值值,它总是有效的,因为它要么来自默认的初始值,要么是由用户正确输入的。我最终在执行验证的 if 语句中调用 RaisePropertyChanged("ShippingWeight") 。如果我把它放在 catch 语句中,如果 MessageBox 也从那里调用,它永远不会被引发。这是进行还原的合理方法还是有更好的方法?这是来自 ViewModel 的代码:

public string ShippingWeight
{
    get { return ShippingModel.ShippingWeight.ToString(); }
    set
    {
    if (ShippingModel.ShippingWeight.ToString() == value) return;

    var oldValue = ShippingModel.ShippingWeight;

    try
    {
        int intValue = Convert.ToInt32(value);

        if (Convert.ToInt32(ShippingParams.ShippingWeightMin) > intValue || Convert.ToInt32(ShippingParams.ShippingWeightMax) < intValue)
        {
            // Revert back to previous value
            // NOTE: This has to be done here. If done in the catch statement, 
            // it will never run since the MessageBox interferes with it.
            RaisePropertyChanged("ShippingWeight");

            throw new Exception();
        }

        ShippingModel.ShippingWeight = intValue;

        RaisePropertyChanged("ShippingWeight", oldValue, Convert.ToDouble(value), true);
    }
    catch (Exception)
    {
        System.Windows.MessageBox.Show("Value must be a whole number between " + ShippingParams.ShippingWeightMin + " and " + ShippingParams.ShippingWeightMax);
    }
}

}

【问题讨论】:

  • 感谢格式修复!

标签: validation windows-phone-7 mvvm-light revert


【解决方案1】:

你可以考虑实现IEditableObject

在调用 BeginEdit 时使用一些私有字段来存储旧值,并在验证失败或用户取消编辑时使用这些值。

【讨论】:

  • 有趣!我一定会多看一看(刚刚看了一眼@@msdn.microsoft.com/en-us/library/…)。我将不得不看看它如何与这段代码的其余部分交互。谢谢。
  • 仅供参考:DataGrid“了解”此接口并在可用时使用它。
猜你喜欢
  • 2011-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多