【发布时间】:2011-06-28 13:10:07
【问题描述】:
我有一个 ItemsControl(比方说一个 ListBox),我有一个 DataTemplate 的内容。当我按下按钮时,我希望验证所有 ListBoxItems。这行得通。
然而,尽管所有项目都经过了正确验证,并且我可以为它们检索错误消息,但 WPF 只显示有问题的 SelectedItem 的 ValidationError.Template 的 ValidationError.Template。对于未通过验证的其他项目,它不会显示 ValidationError.Template。我确实更新了每个项目的绑定源,并将它们的 Validation.HasError 属性设置为 true!只是缺少视觉效果,没有应用样式!
有没有人解决这个问题?
示例
文本框样式:
<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 的触发器将只针对选定的项目设置。
如何解决这个问题?
【问题讨论】:
标签: c# .net wpf xaml itemscontrol