首页 > 解决方案 > 在带有 MVVM 设计模式的代码隐藏中使用文本框粘贴事件?

问题描述

因此,我对 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#wpfmvvmcode-behind

解决方案


恕我直言,一种更清洁的方法是使用INotifyDataErrorInfoValidationRule

它们都在验证方案中占有一席之地。INotifyDataErrorInfo更紧密地绑定到类型,并且ValidationRule松散耦合以验证实例。

以下是有关如何使用验证规则INotifyDataErrorInfo的一些信息


推荐阅读