【发布时间】: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