【发布时间】:2011-07-11 14:33:11
【问题描述】:
我的问题:我想使用控件的 ValidatesOnExceptions 属性验证 TextBox 的用户输入。
XAML 代码:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
...
<TextBox x:Name="TestTextBox" Text="{Binding TestText, Mode=TwoWay, ValidatesOnExceptions=True}" TextChanged="TestTextBox_TextChanged"/>
1 : 使用普通属性的验证工作正常:
ViewModel 代码:
private string _testText,
public string TestText {
get {return _testText;}
set {
if (value=="!")
throw new Exception("Error: No ! allowed!");
_testText = value;
}
}
2:使用依赖属性的验证导致“'System.Exception'类型的第一次机会异常......”并且应用程序停止工作。
ViewModel 代码:
public partial class MyControl : UserControl {
public MyControl() {
InitializeComponent();
}
public static readonly DependencyProperty TestTextProperty = DependencyProperty.Register("TestText", typeof(String), typeof(MyControl), new PropertyMetadata("DefaultText", new PropertyChangedCallback(OnTestTextChanged)));
public event TextChangedEventHandler TestTextChanged;
public String TestText {
get {
return (String)GetValue(TestTextProperty);
}
set {
SetValue(TestTextProperty, value);
if (TestTextChanged != null) {
TestTextChanged(TestTextBox, null);
}
if (TestText=="!") {
throw new Exception("No ! allowed!");
}
}
}
static void OnTestTextChanged(object sender, DependencyPropertyChangedEventArgs args) {
MyControl source = (MyControl)sender;
source.TestTextBox.Text = (String)args.NewValue;
}
private void TestTextBox_TextChanged(object sender, TextChangedEventArgs e) {
TextBox source = (TextBox)sender;
TestText = source.Text;
}
}
我做错了什么?
【问题讨论】:
标签: silverlight validation dependency-properties