c# - 在带有 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 中吗?
解决方案
恕我直言,一种更清洁的方法是使用INotifyDataErrorInfo
或ValidationRule
它们都在验证方案中占有一席之地。INotifyDataErrorInfo
更紧密地绑定到类型,并且ValidationRule
松散耦合以验证实例。
以下是有关如何使用验证规则和INotifyDataErrorInfo的一些信息
推荐阅读
- azure - 在 VM 中使用 Azure CLI 命令
- flutter - Flutter 如何加值并显示
- amazon-web-services - Aws cloudformation - 如何使用字符串参数来防止重复使用相同的字符串
- laravel - Laravel - 我可以将事件绑定到通知吗?
- python - 为什么客户的python包无法导入?
- c# - 如何显示 Windows 桌面通知?
- python - 在 RandomizedSearchCV 中使用 None 和准确度作为评分度量的不同结果
- sharepoint - Microsoft Graph API 文件权限不可见/删除
- c++ - QThread C++中std::thread::join的等价物是什么
- c# - 在 mysql 中使用 JSON_ARRAY 和 JSON_OBJECT 后无法将 json 解析为 JArray 对象