我不確定您是否只是想驗證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>
或者,你可以這樣定義
風格3210
如果你正在嘗試創建一個自定義控件,這個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" .../>