在WPF中从代码设置验证错误模板

14

我在我的WPF应用程序中有一个TextBox。我已经定义了一个控件模板来验证错误,如下:

<ControlTemplate x:Key="validationTemplate">
    <DockPanel LastChildFill="True">
         <TextBlock DockPanel.Dock="Bottom"  Text="Invalid Input: "></TextBlock>
                 <AdornedElementPlaceholder />
    </DockPanel>
</ControlTemplate>
我的文本框如下:
<TextBox Validation.ErrorTemplate="{StaticResource validationTemplate}">                                              
    <TextBox.Text>
        <Binding Path="TEXT1" ValidatesOnDataErrors="True" validatesOnExceptions="True">
         </Binding>
    </TextBox.Text>
</TextBox>

如果我给我的TextBox添加了ValidationRule,然后进行验证,错误模板就可以正确地应用。但由于其他问题,我不能这样做。

所以我必须在PreviewLostKeyboardFocus中验证TextBox的内容。我正在验证TextBox。现在我想在代码后台为TextBox设置错误模板,但是我无法实现它!

我尝试过这个,但它没有按预期工作:

private void blockTextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        TextBox txtBox = sender as TextBox;
        txtBox.Template = this.FindResource("validationTemplate") as ControlTemplate;

        //this behaves strange; it removes the TextBox and places the ErrorTemplate. 
       //I want it to behave like the way WPF does internally wherein it places 
       //the error template around TExtBox
    }

问题1:我想知道如何将错误模板添加到TextBox中。

问题2:我想知道如何从代码中设置控件模板的错误消息。例如,我想将默认的错误消息“Invalid Input:”更改为“Invalid Input: Please enter correct input”。

我只想在代码后台执行上述操作!

编辑1:

问题是我如何从代码后台将Validation.HasError设置为true,因为我没有使用任何验证器。(或者我应该如何从代码后台设置才能应用ValidationTemplate?)

编辑2:

我正在进行XML绑定,所以无法实现IDataErrorInfo! 我只想从代码后面实现这一点!!有办法可以从代码后面设置Validation.HasError吗?

4个回答

24

要在代码后台设置“Validation.HasError”,可以使用Validation.MarkInvalid方法。

private void blockTextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) 
{ 
    TextBox txtBox = sender as TextBox;
    //...
    BindingExpression bindingExpression =
        BindingOperations.GetBindingExpression(txtBox, TextBox.TextProperty);

    BindingExpressionBase bindingExpressionBase = 
        BindingOperations.GetBindingExpressionBase(txtBox, TextBox.TextProperty);

    ValidationError validationError =
        new ValidationError(new ExceptionValidationRule(), bindingExpression);

    Validation.MarkInvalid(bindingExpressionBase, validationError);
}

要取消设置的值,您可以使用

Validation.ClearInvalid

5
感谢他给我推荐的精彩链接。我的代码大致如下:
String errorMessage = GetFormattedErrorMessage(toolTip.Range, range);
ValidationError validationError = new ValidationError(new DummyValidator(),
txtBox.GetBindingExpression(TextBox.TextProperty));
Validation.MarkInvalid(txtBox.GetBindingExpression(TextBox.TextProperty), validationError);
validationError.ErrorContent = errorMessage;
Validation.SetErrorTemplate(txtBox, GetErrorTemplate(errorMessage));

4
Validation.SetErrorTemplate(txtBox, this.FindResource("validationTemplate") as ControlTemplate);

对于您的问题#2,您可以动态创建一个带有适当错误消息的“ControlTemplate”,并将其分配给一个“Control”。 - decyclone
@decyclone :: 但问题是,我如何在代码后端将Validation.HasError设置为true,因为我没有使用任何验证器。 - Gurucharan Balakuntla Maheshku
使用 IDataErrorInfo 接口(http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo.aspx)将绑定到此控件的对象标记为无效。 - decyclone
@decyclone:我正在进行XML绑定,所以我无法实现IDataErrorInfo!!有没有办法从代码后台设置Validation.HasError?? - Gurucharan Balakuntla Maheshku
我不确定,但你是否尝试过类似以下的代码:textBox1.SetValue(Validation.HasErrorProperty, true); - decyclone
@decyclone:它不起作用!!我得到了这个异常 {'HasError' 属性已被注册为只读,没有授权密钥无法修改。} :( - Gurucharan Balakuntla Maheshku

1

关于您的第一个问题。您可以在代码后端设置ErrorTemplate,例如:

    public MainWindow()
    {
        InitializeComponent();

        var template = this.FindResource("validationTemplate") as ControlTemplate;
        Validation.SetErrorTemplate(this.textBox1, template);
     }


编辑: 针对您的第二个问题,请参考以下示例。 sites.google.com/site/html5tutorials/ValidationErrorText.zip


但问题是,我如何在代码后端将Validation.HasError设置为true,因为我没有使用任何验证器。 - Gurucharan Balakuntla Maheshku
你需要创建一个ValidationRule。不创建ValidationRule有什么具体原因吗? - Prince Ashitaka
是的,由于我有很多限制条件,所以我无法使用验证规则!这是一个大项目,我必须这样做:( 请问您知道如何在文本框上设置错误属性吗? - Gurucharan Balakuntla Maheshku
1
最少情况下,您需要创建验证规则。请检查此链接是否有所帮助 http://www.wpftutorial.net/ValidationErrorByCode.html但是,错误属性不应直接设置! - Prince Ashitaka

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接