WPF ListBox ErrorTemplate

В моем приложении WPF есть привязка ListBox к коллекции моделей представлений. Эти модели представления поддерживают проверку путем реализации INotifyDataErrorInfo. Я пытаюсь отобразить шаблон ошибки для элементов с ошибками проверки в моем ListBox.

Я могу получить ListBox для отображения шаблона ошибки по умолчанию, установив NotifyOnValidationError=True в привязке ItemSource ListBox.
Который выглядит так: введите описание изображения здесь

Код моего ListBox:

<ListBox x:Name="ListBoxEvents" ItemsSource="{Binding Events, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True}" 
                 IsSynchronizedWithCurrentItem="True" ItemTemplate="{DynamicResource EventListTemplate}"></ListBox>

Мой стиль ListBox:

<ControlTemplate x:Key="ListBoxValidationError">
    <DockPanel LastChildFill="True">
        <Border Background="Red" Margin="5">
            <AdornedElementPlaceholder />
        </Border>
    </DockPanel>
</ControlTemplate>

<Style TargetType="{x:Type ListBox}">
    <Setter Property="BorderBrush" Value="{StaticResource WindowTitleBrush}" />
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="MinWidth" Value="200" />
    <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
    <Setter Property="ScrollViewer.CanContentScroll" Value="False"></Setter>
    <Setter Property="Validation.ErrorTemplate" Value="{StaticResource ListBoxValidationError}"></Setter>
</Style>

Шаблон элемента ListBox:

<DataTemplate x:Key="EventListTemplate" DataType="{x:Type event:EventViewModel}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

       <TextBlock Text="{Binding Title, Converter={StaticResource EmptyStringConverter}, ConverterParameter='-'}" FontWeight="Bold" FontSize="14" />
        <TextBlock Text="{Binding Date, StringFormat={}{0:dd.MM.yyyy}}" Grid.Row="1" Grid.Column="0" FontStyle="Italic" />
        <Button Grid.Column="1" Grid.RowSpan="2" Grid.Row="0" Style="{DynamicResource ItemDeleteButton}" />
    </Grid>
</DataTemplate>

Как я могу отобразить пользовательский шаблон ошибки для моих ListBoxItems? (Моя цель - сделать фон элементов красным)

1 ответ

Решение

Вы можете указать Valdiation.ErrorTemplate на ListBoxItem, а также в ItemContainerStyle:

<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <Border Background="Red" Opacity="0.2">
                            <AdornedElementPlaceholder/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Скорее всего, вы хотите показать его в ListBoxItem, когда какое-либо свойство в элементе выдает ошибку. Недопустимое свойство Say Name в данных ListBoxItem, которое привязано к TextBox. Задавать ValidatesOnDataErrors true в текстовом поле и установите Validation.ValidationAdornerSite в родительский ListBoxItem.

Для образца:

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
                     Validation.ValidationAdornerSite="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <Border Background="Red" Opacity="0.2">
                           <AdornedElementPlaceholder/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>
Другие вопросы по тегам