我创建了一个小型用户控件来扩展我的验证乐趣!问题是验证不起作用:永远不会调用 IDataErrorInfo.this[]。
预先感谢您的帮助。斯蒂芬
这是我的代码:
<UserControl x:Class="WpfApplication5.TextBoxWithValidation"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="TextBoxWithValidationControl">
<Grid>
<StackPanel Orientation="Horizontal">
<TextBox Height="23" Width="120"
Text="{Binding Path=Text,ElementName=TextBoxWithValidationControl, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}">
</TextBox>
</StackPanel>
</Grid>
后面的代码是:
public partial class TextBoxWithValidation
{
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text",
typeof (object),
typeof (
TextBoxWithValidation
),
new FrameworkPropertyMetadata
(default(object),
FrameworkPropertyMetadataOptions
.BindsTwoWayByDefault));
public TextBoxWithValidation()
{
InitializeComponent();
}
public object Text
{
get { return GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
}
现在我正在使用这个用户控件:
<local:TextBoxWithValidation Text="{Binding Path=Dummy.MyProperty}" />
我的虚拟实体定义为:
public class Dummy : INotifyPropertyChanged, IDataErrorInfo
{
private string _myProperty;
public string MyProperty
{
get { return _myProperty; }
set
{
_myProperty = value;
OnPropertyChanged("MyProperty");
}
}
#region IDataErrorInfo Members
public string this[string columnName]
{
get { return "This is an error"; }
}
public string Error { get; private set; }
#endregion
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}