我有一个ItemsControl(比如说一个ListBox),并且我有一个用于内容的DataTemplate。当我按下一个按钮时,我想要验证所有的ListBoxItems。这个可以实现。
然而,尽管所有的项目都被正确验证,并且我可以检索到它们的错误信息,但WPF仅显示了涉及的ListBox的SelectedItem的ValidationError.Template。它没有显示其他未通过验证的项目的ValidationError.Template。我确实为每个项目更新了绑定源,并且Validation.HasError属性对它们设置为true!只是视觉效果缺失,样式没有被应用!
有人有这个问题的解决方案吗?
示例:
一个TextBox的样式:
一个用于人员实体的数据模板:
然而,尽管所有的项目都被正确验证,并且我可以检索到它们的错误信息,但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
触发器仅会对所选项目进行设置。
如何解决这个问题?