为什么我的 WPF 验证错误没有显示?
我已经定义了一个用于显示验证错误的控件模板:
<ControlTemplate x:Key="validationTemplate">
<DockPanel LastChildFill="True">
<TextBlock DockPanel.Dock="Right"
Background="Red"
TextWrapping="Wrap">
<TextBlock.Text>
<Binding Path="(Validation.Errors)[0].ErrorContent"
RelativeSource="{x:Static RelativeSource.Self}">
</Binding>
</TextBlock.Text>
</TextBlock>
<AdornedElementPlaceholder ></AdornedElementPlaceholder>
</DockPanel>
</ControlTemplate>
我已经定义了一个文本框,如下所示:
<TextBox Text="{Binding Text}" PreviewTextInput="textBox1_PreviewTextInput"
Validation.ErrorTemplate="{StaticResource validationTemplate}" />
我正在从后面的代码设置验证,如下所示:
private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
TextBox txtBox = (TextBox)sender;
....
....
ValidationError validationError = new ValidationError(new DummyValidator(),
txtBox.GetBindingExpression(TextBox.TextProperty));
Validation.MarkInvalid(txtBox.GetBindingExpression(TextBox.TextProperty), validationError);
validationError.ErrorContent = "This is wrong input";
e.Handled = true;
}
现在的问题是验证正在被触发,并且显示了红色条,但内部的错误消息没有显示! 可能是我错了
它在控制台中抛出一些异常(索引越界异常)
<Binding Path="(Validation.Errors)[0].ErrorContent"
RelativeSource="{x:Static RelativeSource.Self}">
请指导我我哪里出错了?
I have defined a control template for showing Validation Errors:
<ControlTemplate x:Key="validationTemplate">
<DockPanel LastChildFill="True">
<TextBlock DockPanel.Dock="Right"
Background="Red"
TextWrapping="Wrap">
<TextBlock.Text>
<Binding Path="(Validation.Errors)[0].ErrorContent"
RelativeSource="{x:Static RelativeSource.Self}">
</Binding>
</TextBlock.Text>
</TextBlock>
<AdornedElementPlaceholder ></AdornedElementPlaceholder>
</DockPanel>
</ControlTemplate>
I have defined a TextBox as follows:
<TextBox Text="{Binding Text}" PreviewTextInput="textBox1_PreviewTextInput"
Validation.ErrorTemplate="{StaticResource validationTemplate}" />
I am setting the validation from code behind as follows:
private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
TextBox txtBox = (TextBox)sender;
....
....
ValidationError validationError = new ValidationError(new DummyValidator(),
txtBox.GetBindingExpression(TextBox.TextProperty));
Validation.MarkInvalid(txtBox.GetBindingExpression(TextBox.TextProperty), validationError);
validationError.ErrorContent = "This is wrong input";
e.Handled = true;
}
Now the problem is The Validation is getting fired and a red strip is shown but the error message inside that is not getting displayed!!
May be I am wrong with this
It is throwing some exception in console (index out of bounds exception)
<Binding Path="(Validation.Errors)[0].ErrorContent"
RelativeSource="{x:Static RelativeSource.Self}">
Please guide me regarding Where am I going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的相对来源是错误的
Your RelativeSource is wrong