我不确定您是想向TextBox 添加验证还是创建自定义控件。如果您正在为验证而苦苦挣扎,这个post 提供了一个非常好的概述。总之,你可以做这样的事情
public class ViewModel : System.ComponentModel.IDataErrorInfo
{
public ViewModel()
{
/* Set default age */
this.Age = 30;
}
public int Age { get; set; }
public string Error
{
get { return null; }
}
public string this[string columnName]
{
get
{
switch (columnName)
{
case "Age":
if (this.Age < 10 || this.Age > 100)
return "The age must be between 10 and 100";
break;
}
return string.Empty;
}
}
}
然后像这样使用它
<TextBox Text="{Binding Path=Age, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"/>
如果您想创建自己的错误模板,您可以像这样为个人TextBox 做它
<TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}">
<Validation.ErrorTemplate>
<ControlTemplate>
<StackPanel>
<!-- Placeholder for the TextBox itself -->
<AdornedElementPlaceholder x:Name="textBox"/>
<TextBlock Text="{Binding [0].ErrorContent}" Foreground="Red"/>
</StackPanel>
</ControlTemplate>
</Validation.ErrorTemplate>
</TextBox>
或者,您可以定义这样的样式
<Style TargetType="x:TextBox">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<StackPanel>
<AdornedElementPlaceholder/>
<TextBlock Text="{Binding [0].ErrorContent}" Foreground="Red"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
如果您尝试创建自定义控件,则此 post 和此 question 值得一看。关键部分是像这样向您的控件添加DependencyProperty
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MyTextBox), new PropertyMetadata(string.Empty, OnTextChangedCallback));
private static void OnTextChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Validation in here
}
那么你可以这样使用它
<MyTextBox Text="My Text" .../>