验证ItemsControl中的项的数据模板

4
我有一个ItemsControl(比如说一个ListBox),并且我有一个用于内容的DataTemplate。当我按下一个按钮时,我想要验证所有的ListBoxItems。这个可以实现。
然而,尽管所有的项目都被正确验证,并且我可以检索到它们的错误信息,但WPF仅显示了涉及的ListBox的SelectedItem的ValidationError.Template。它没有显示其他未通过验证的项目的ValidationError.Template。我确实为每个项目更新了绑定源,并且Validation.HasError属性对它们设置为true!只是视觉效果缺失,样式没有被应用!
有人有这个问题的解决方案吗?
示例:
一个TextBox的样式:
<Style TargetType="{x:Type TextBox}">
    <Setter Property="Validation.ErrorTemplate">
        <Setter.Value>
            <ControlTemplate>
                <DockPanel LastChildFill="True">
                        <AdornedElementPlaceholder Name="MyAdorner" />
                </DockPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

    <Setter Property="Background" Value="{DynamicResource TextBoxBackgroundBrush}" />
    <Style.Triggers>
        <Trigger Property="IsFocused" Value="true">
            <Setter Property="Background" Value="{DynamicResource TextBoxFocusBackgroundBrush}" />
        </Trigger>
        <Trigger Property="Validation.HasError" Value="true">
            <Setter Property="Background" Value="{DynamicResource ErrorBrush}" />
            <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
        </Trigger>
    </Style.Triggers>

</Style>

一个用于人员实体的数据模板:
<DataTemplate DataType="{x:Type entities:Person}" x:Key="PersonItemStyle">
    <Grid>
        <TextBox x:Name="SomeTextBox">
            <TextBox.Text>
               <Binding Path="Name" UpdateSourceTrigger="PropertyChanged">
                   <Binding.ValidationRules>
                            <validators:RequiredFieldValidationRule ErrorMessage="Please enter a name!" />
                   </Binding.ValidationRules/>
               </Binding>
            </TextBox.Text>
        </TextBox>
    </Grid>
</DataTemplate>

在某个控件中:

        <ListBox Grid.Row="1" x:Name="ListBoxPersons" Style="{DynamicResource ListBoxStyle}" ItemsSource="{Binding Path=Persons}" 
ItemContainerStyle="{StaticResource PersonItemStyle}">
        </ListBox>

那么尝试编辑一些人员信息,例如将其名称设置为null或使用任何错误的绑定方式。当你进行验证时,Validation.HasError触发器仅会对所选项目进行设置。

如何解决这个问题?

1个回答

0
你正在将ItemContainerStyle设置为DataTemplate,为什么?该样式应用于所有文本框,因此您不必单独设置ItemContainerStyle。

这与问题完全无关。数据模板需要包括Person-Entity的验证器。为实体创建数据模板是完全可以的。 - Falcon

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