只有使用Validation.HasError触发属性WPF当假的风格显示属性、风格、Validation、HasError

2023-09-07 10:30:40 作者:妳給我的爛借口

我有,我只希望允许数值是输入文本框自定义样式。

I have a custom style for a text box that I only want to allow numerical values to be input.

我创建了一个自定义的有效性规则来检查这一点。

I have created a custom ValidationRule to check for this.

如果输入的是有效的我要显示一个绿色的边框,如果不是我想显示一个红色的边框。当有但是绿当输入正确不正确显示一个错误的红色边框显示正确,它只是显示的文本框的默认值。

If the input is valid I want to display a green border and if not I want to display a red border. The red border is displayed correctly when there is an error however the green is not displayed correctly when the input is correct, it just displays textbox defaults.

在我的自定义有效性规则的ValidateResult方法是:

The ValidateResult method in my custom ValidationRule is:

 public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {            
        string input = (value ?? String.Empty).ToString();
        double val;
        if (double.TryParse(input, out val))
        {
            return new ValidationResult(true, OkMessage);
        }
        else return new ValidationResult(false, ErrorMessage);
    }

的样式和触发器的定义:

The Style and Triggers are defined:

<Style TargetType="{x:Type TextBox}">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true">
                <Setter Property="Validation.ErrorTemplate">
                    <Setter.Value>
                        <ControlTemplate>                                
                                <Border BorderBrush="Red" BorderThickness="1"/>
                            </DockPanel>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Trigger>
            <Trigger Property="Validation.HasError" Value="False">
                <Setter Property="Validation.ErrorTemplate">
                    <Setter.Value>
                        <ControlTemplate>                                
                                <Border BorderBrush="Green" BorderThickness="1"/>
                            </DockPanel>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>

我怎样才能得到边框显示绿色时,输入正确的验证?

How can I get the border to display green when the input is correctly validated?

推荐答案

我相信这是因为 Validation.HasError 是清零时,有的没有错误,未设置为为您的触发需要。为什么不直接包括在模板中的绿色边框?该HasError触发器将其更改为红色,而在其他时间应该是绿色的所以最好只把内联,而不是一个触发器。

I believe this is because Validation.HasError is cleared when there is no error, not set to false as your trigger requires. Why not just include the green border in your template? The HasError trigger will change it to red, but at all other times it should be green so best just to place that inline rather than a trigger.