我有一个 ItemsControl(比方说一个 ListBox),我有一个用于内容的 DataTemplate
。当我按下按钮时,我希望验证所有 ListBoxItems。这行得通。
然而,尽管所有项目都经过正确验证并且我可以检索它们的错误消息,WPF 只显示 的
有问题。对于未通过验证的其他项目,它不会显示 SelectedItem
的 ValidationError.Template
ListBoxValidationError.Template
。我确实更新了每个项目的绑定(bind)源,并将它们的 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 或使用任何错误的绑定(bind)。当您验证时,Validation.HasError
的触发器将仅为所选项目设置。
如何解决这个问题?
最佳答案
您正在将 ItemContainerStyle 设置为 DataTemplate,为什么?该样式应用于所有文本框,因此您不必单独设置 ItemContainerStyle。
关于c# - 验证项目控件中项目的数据模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6506952/