我想确定的第一件事是,你真的想做一个CustomControl而不是一个UserControl。我相信question基本上和你的一样,只是措词不同而已。
UserControl比自定义控件更适合MVVM模式,因为您将有.xaml(和.xaml.cs)文件以及.cs文件作为ViewModel。另一方面,CustomControl永远不会用MVVM完成,因为视觉外观(视图)是通过ControlTemplate定义和覆盖的。
既然你说过你有View和ViewModel,那么让我们考虑一下你将如何用你的文本框实现你想要的行为。您的文本框必须验证并拒绝超出您所需值范围的用户输入。这意味着您的View代码隐藏必须具有属性和逻辑,以控制View中定义的文本框输入值的限制。你已经在这里违反了MVVM。
当你说你有一个视图,这让我觉得你正在编写一个UserControl。但是您的需求(文本框的自定义行为)表明您确实需要一个CustomControl,您不使用MVVM。
如果你同意,你需要一个CustomControl,这里有一个快速和肮脏的例子:
public class RestrictedTextBox : TextBox
{
public static readonly DependencyProperty MaxValueProperty = DependencyProperty.Register("MaxValue", typeof(int), typeof(RestrictedTextBox), new PropertyMetadata(int.MaxValue));
public RestrictedTextBox()
{
PreviewTextInput += RestrictedTextBox_PreviewTextInput;
}
public int MaxValue
{
get
{
return (int)GetValue(MaxValueProperty);
}
set
{
SetValue(MaxValueProperty, value);
}
}
private void RestrictedTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
int inputDigits;
RestrictedTextBox box = sender as RestrictedTextBox;
if (box != null)
{
if (!e.Text.All(Char.IsDigit))
{
// Stops the text from being handled
e.Handled = true;
}
else if (int.TryParse(box.Text + e.Text, out inputDigits))
{
if (inputDigits > MaxValue)
e.Handled = true;
}
}
}
}
XAML用法:
<local:RestrictedTextBox MaxValue="100"></local:RestrictedTextBox>
这个帖子最初读“定制”的控制,我事实上是在试图创建用户控件 –