【问题标题】:Using Textbox pasting event in Code Behind with MVVM Design Pattern?在带有 MVVM 设计模式的代码中使用文本框粘贴事件?
【发布时间】:2019-01-27 02:44:27
【问题描述】:

所以我不熟悉 WPF 中使用的流行 MVVM 设计模式。我有一个文本框,我只想接受数字输入。目前,我的用户控件已将其 DataContext 设置为我的 ViewModel。我的问题是下面的代码是否也应该在我的 ViewModel 中,或者按照 MVVM 设计模式将它放在我的用户控件(视图)中是否可以?

private static readonly Regex num = new Regex("[^0-9.-]+");

private void ValidationEvent(object sender, TextCompositionEventArgs e)
{
    e.Handled = num.IsMatch(e.Text);
}

private void PastingEvent(object sender, DataObjectPastingEventArgs e)
{
    if (e.DataObject.GetDataPresent(typeof(String)))
    {
        if (num.IsMatch((String)e.DataObject.GetData(typeof(String))))
        {
            e.CancelCommand();
        }
    }
    else
    {
        e.CancelCommand();
    }
}

这些事件在我的视图中绑定到一个文本框,如下所示:

<TextBox Text="{Binding Number}" DataObject.Pasting="PastingEvent" PreviewTextInput="ValidationEvent" Width="70" Margin="5 5 10 5" Style="{StaticResource PlaceHolderTextBox}" />

根据最佳实践,所有这些都应该在关联的 ViewModel 中吗?

【问题讨论】:

    标签: c# wpf mvvm code-behind


    【解决方案1】:

    恕我直言,更简洁的方法是使用 INotifyDataErrorInfoValidationRule

    它们在验证方案中都有自己的位置。 INotifyDataErrorInfo 更紧密地绑定到类型,ValidationRule 松散耦合以验证实例。

    这里有一些关于如何使用Validation RulesINotifyDataErrorInfo的信息

    【讨论】:

    • 我对此进行了研究,特别是 INotifyDataErrorInfo,感觉就像是让用户知道他的输入不正确而不是简单地阻止他首先输入错误输入的一种不必要的迂回方式。为什么你会推荐这个而不是我上面提到的两个功能?
    • 好点。 1-可重用的代码。 2-View 不负责验证。
    猜你喜欢
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    相关资源
    最近更新 更多