Измените дочерний элемент управления из триггера или лучший способ изменить их передний план? - PullRequest
1 голос
/ 29 мая 2020

У меня есть список с шаблоном, внутри элемента списка у меня есть 2 текстовых блока.

Моя цель - изменить передний план этих 2 текстовых блоков, когда элемент списка:

  • Наведение (наведение указателя мыши)
  • Выбрано

My ItemTemplate в настоящее время удаляет выделение, когда вы наводите курсор на элементы, что работает должным образом.

Я знаю, что могу получить События IsSelected и IsMouseOver, например:

<Trigger Property="IsSelected" Value="true">
    <Setter Property="Background" TargetName="Bd" Value="White"/>
    <!-- I have no idea how to access the textblock child of the listboxitem to change it -->
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
    <!-- I have no idea how to access the textblock child of the listboxitem to change it -->
</Trigger>

Но я не мог понять, как изменить TextBlock внутри, я пробовал использовать acestor и другими способами, ни один из которых не работал (поскольку они не имели никакого эффекта ).

Вот как выглядит мой вид:

<UserControl x:Class="Shex.Views.SideBarView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:Shex.Views"
             xmlns:s="https://github.com/canton7/Stylet"
             xmlns:shex="clr-namespace:Shex"
             mc:Ignorable="d" 
             d:DesignHeight="800" d:DesignWidth="260"
             Background="#403f42" Padding="0" BorderThickness="0" Margin="0">
    <UserControl.Resources>
        <Style x:Key="MenuContainerStyle" TargetType="{x:Type ListBoxItem}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ListBoxItem}">
                        <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" 
                                BorderThickness="0" Background="{TemplateBinding Background}" 
                                Padding="0" SnapsToDevicePixels="true"> 
                            <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                              SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
                                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsSelected" Value="true">
                                <Setter Property="Background" TargetName="Bd" Value="White"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>
    <Grid Margin="0">
        <ListBox ItemsSource="{Binding MenuItems}" SelectionMode="Single" SelectedItem="{Binding SelectedMenuItem}" SelectionChanged="{s:Action ChangeView}"
                 BorderThickness="0" Padding="0" Margin="0 10 0 0" Background="#403f42" ItemContainerStyle="{DynamicResource MenuContainerStyle}" SnapsToDevicePixels="true">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Height="60" Orientation="Horizontal" SnapsToDevicePixels="true">
                        <TextBlock Text="{Binding Image}" FontFamily="/Shex;component/Fonts/Font Awesome 5 Free-Solid-900.otf#Font Awesome 5 Free Solid" Foreground="#cfced1" FontSize="20" Margin="10 6 0 0" Width="30" VerticalAlignment="Center" HorizontalAlignment="Left"/>
                        <TextBlock Text="{Binding Name}" Foreground="#cfced1" FontSize="20" Margin="10 6 0 0" VerticalAlignment="Center" HorizontalAlignment="Left"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</UserControl>

Ответы [ 2 ]

1 голос
/ 29 мая 2020

Вы должны добавить триггер (ы) к ItemTemplate, например:

<DataTemplate>
    <StackPanel ...>
        <TextBlock x:Name="tb1" ... />
        <TextBlock x:Name="tb2" ... />
    </StackPanel>
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=ListBoxItem}}" Value="True">
            <Setter TargetName="tb1" Property="Foreground" Value="Blue" />
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

Стиль ListBoxItem не может устанавливать свойства какого-либо отдельного TextBlock или любого другого элемента управления, который определен в ItemTemplate.

0 голосов
/ 29 мая 2020

Другой и даже более простой способ сделать это:

Удалите свойство Foreground из TextBlocks и добавьте его в стиль ListBoxItem.

<Style x:Key="MenuContainerStyle" TargetType="{x:Type ListBoxItem}">
        <!--Foreground for normal state-->
        <Setter Property="Foreground" Value="#cfced1"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" 
                            BorderThickness="0" Background="{TemplateBinding Background}" 
                            Padding="0" SnapsToDevicePixels="true">
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                          SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
                                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="true">
                            <Setter Property="Background" TargetName="Bd" Value="White"/>
                            <!--Foreground when selected-->
                            <Setter Property="Foreground" Value="Red"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Grid Margin="0">
    <ListBox SelectionMode="Single" ItemsSource="{Binding MenuItems}" 
             BorderThickness="0" Padding="0" Margin="0 10 0 0" Background="#403f42" ItemContainerStyle="{DynamicResource MenuContainerStyle}" SnapsToDevicePixels="true">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Height="60" Orientation="Horizontal" SnapsToDevicePixels="true">
                    <TextBlock Text="{Binding Image}" FontFamily="/Shex;component/Fonts/Font Awesome 5 Free-Solid-900.otf#Font Awesome 5 Free Solid" FontSize="20" Margin="10 6 0 0" Width="30" VerticalAlignment="Center" HorizontalAlignment="Left"/>
                    <TextBlock Text="{Binding Name}" FontSize="20" Margin="10 6 0 0" VerticalAlignment="Center" HorizontalAlignment="Left"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>
...