問題:コントロールのValidatesOnExceptionsプロパティを使用してTextBoxのユーザー入力を検証したいと思います。DependencyPropertyにデータバインドされた入力を検証する - Silverlight
XAMLコード:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
...
<TextBox x:Name="TestTextBox" Text="{Binding TestText, Mode=TwoWay, ValidatesOnExceptions=True}" TextChanged="TestTextBox_TextChanged"/>
1:通常のプロパティを使用して検証が正常に動作:
ビューモデルコード:
private string _testText,
public string TestText {
get {return _testText;}
set {
if (value=="!")
throw new Exception("Error: No ! allowed!");
_testText = value;
}
}
2:依存関係プロパティを使用して検証は、「Aを引き起こします'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;
}
}
は私が間違って何をしているのですか?
私は、OPが匿名でコードを匿名化しているので、その行に 'if(TestText ="! ")という行があると思われます。 C#の 'if'文の条件は' bool'型でなければならないので、上記のコードはコンパイルされませんが、 'TestText ="! "'という型は 'string'型です。 –
ああ、代わりに警告を投げるかもしれないと思った。 – StephenT