1

我正在使用 IDataErrorInfo 在 WPF 中的表单中验证我的数据。我在我的演示者中实施了验证。

实际验证正在发生,但应该更新 UI 和设置样式的 XAML 没有发生。

这里是:

  <Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true">
                <Setter Property="ToolTip"
                    Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                Path=(Validation.Errors)[0].ErrorContent}"/>
                    <Setter Property="Background" Value="Red"/>
                </Trigger>
        </Style.Triggers>
    </Style>

问题是我的绑定不Validation.Errors包含数据。如何从 Presenter 类中获取这些数据并将其传递给此 XAML 以更新 UI 元素?

编辑:

文本框:

 <TextBox Style="{StaticResource textBoxInError}" Name="txtAge" Height="23" Grid.Row="3" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Width="150">
            <TextBox.Text>
                <Binding Path="StrAge" Mode="TwoWay"
                         ValidatesOnDataErrors="True"
                         UpdateSourceTrigger="PropertyChanged"/>
            </TextBox.Text>

验证发生,但数据无效时应用的样式没有发生。

4

2 回答 2

2

您是否在绑定表单时查看了输出窗口?通过在绑定发生时查看输出,可以发现大量验证问题。

还有一个简短的说明:

利用

Path=(Validation.Errors).CurrentItem.ErrorContent

而不是

Path=(Validation.Errors)[0].ErrorContent

当向控件提供有效值时,它将为您节省一些进一步的绑定异常

于 2010-11-02T16:50:25.663 回答
1

我注意到你的风格还没有完全完成。

Style 需要一个定义“Validation.ErrorTemplate”的控件模板,以便在发生验证错误时工作。尝试进行以下更改,看看它是如何进行的。

Paul Stovell 有一篇关于 WPF 验证的非常好的文章它将涵盖您需要的大部分内容。我还在这里写了一篇文章简化您可能也喜欢的验证。

<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="true">
            <Setter Property="ToolTip"
                Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                Path=(Validation.Errors)[0].ErrorContent}"/>
            <Setter Property="Background" Value="Red"/>
        </Trigger>
    </Style.Triggers>
</Style>

<Style  x:Key="textBoxInError" TargetType="{x:Type TextBox}">
    <Setter Property="Validation.ErrorTemplate">
        <Setter.Value>
            <ControlTemplate>
                <Border BorderBrush="Red" BorderThickness="1">
                    <AdornedElementPlaceholder />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="true">
            <Setter Property="ToolTip"
                Value="{Binding RelativeSource={RelativeSource Self}, 
                       Path=(Validation.Errors)[0].ErrorContent}"/>
        </Trigger>
    </Style.Triggers>
</Style>
于 2010-03-16T10:24:33.370 回答