为什么我的WPF验证错误没有显示?

时间:2010-11-26 11:53:50

标签: wpf validation controltemplate

我已经定义了一个用于显示验证错误的控制模板:

<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,如下所示:

<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}">  

请指导我哪里出错?

1 个答案:

答案 0 :(得分:0)

<Binding Path="(Validation.Errors)[0].ErrorContent"
    RelativeSource="{x:Static RelativeSource.Self}">

您的RelativeSource错误

<Binding Path="(Validation.Errors)[0].ErrorContent"
    RelativeSource="{RelativeSource Self}">