WPF C# ListBox IsMouseOver и IsSelected фон - PullRequest
1 голос
/ 22 апреля 2020

Я сделал следующий пользовательский контроль, и все работает хорошо, за исключением двух свойств установщика фона со значением прозрачного для isMouseOver и IsSelected, которые ничего не делают ..

<UserControl.Resources>
        <DataTemplate x:Key="DeviceItemTemplate">
            <Border Padding="10,5" Margin="10" BorderThickness="4" BorderBrush="Green" CornerRadius="20" Height="150" Width="150">
                <StackPanel Orientation="Vertical">
                    <TextBox Name="screenNameTextBox"
                                 Margin="10" Height="20"
                                 Text="{Binding Name}" />
                    <TextBox
                                 Margin="10" Height="20"
                                 Text="{Binding Location}" />
                </StackPanel>
            </Border>
        </DataTemplate>

        <DataTemplate x:Key="DeviceItemTemplateSelected">
            <Border Padding="10,5" Margin="10" BorderThickness="4" BorderBrush="Orange" CornerRadius="20" Height="150" Width="150" >
                <StackPanel Orientation="Vertical" >
                    <TextBox Name="screenNameTextBox"
                                 Margin="10" Height="20"
                                 Text="{Binding Name}" />
                    <TextBox
                                 Margin="10" Height="20"
                                 Text="{Binding Location}" />
                </StackPanel>
            </Border>
        </DataTemplate>

        <Style TargetType="{x:Type ListBoxItem}" x:Key="DeviceContainerStyle">
            <Setter Property="ContentTemplate" Value="{DynamicResource DeviceItemTemplate}"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True" >
                    <Setter Property="BorderThickness" Value="0" />
                    <Setter Property="Background" Value="Transparent" />
                </Trigger>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="ContentTemplate" Value="{DynamicResource DeviceItemTemplateSelected}"/>
                    <Setter Property="BorderThickness" Value="0" />
                    <Setter Property="Background" Value="Transparent" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </UserControl.Resources>

    <Border
        Grid.Column="0"
        Margin="10"
        BorderBrush="Silver"
        BorderThickness="1">

        <ListBox ItemsSource="{Binding Devices, UpdateSourceTrigger=PropertyChanged}"
                    SelectedItem="{Binding SelectedScreen, Mode=TwoWay}" 
                    ItemContainerStyle="{StaticResource DeviceContainerStyle}"
                    ScrollViewer.HorizontalScrollBarVisibility="Disabled"   >

            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel IsItemsHost="True" Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
    </Border>

Вот как это выглядит

enter image description here

Я также пробовал белый, но получил те же результаты. Я не могу избавиться от этого синего фона.

Что я пропускаю, пожалуйста? ----- После получения ответа mm8 -----

Поместил весь свой код в словарь ресурсов, внес некоторые изменения в solidcolorbru sh и BorderThickness и изменил раздел стиля от предыдущего до:

<Style BasedOn="{StaticResource ListBoxItemSSDS}" TargetType="{x:Type ListBoxItem}" x:Key="DeviceContainerStyle">
            <Setter Property="ContentTemplate" Value="{DynamicResource DeviceItemTemplate}"/>
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="ContentTemplate" Value="{DynamicResource DeviceItemTemplateSelected}"/>
                </Trigger>
            </Style.Triggers>
        </Style>

1 Ответ

1 голос
/ 22 апреля 2020

Вам необходимо определить пользовательский ControlTemplate для ListBoxItem, чтобы иметь возможность использовать его на заднем фоне, когда установлены свойства IsMouseOver и IsSelected.

Вы можете щелкнуть правой кнопкой мыши на ListBoxItem в режиме разработки в Visual Studio или в Blend и выбрать «Редактировать шаблон» -> «Редактировать копию», чтобы скопировать шаблон по умолчанию в разметку XAML, а затем отредактировать его согласно требования.

Вот как это выглядит и какие ресурсы задействованы:

<Style x:Key="FocusVisual">
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate>
                <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<SolidColorBrush x:Key="Item.MouseOver.Background" Color="#1F26A0DA"/>
<SolidColorBrush x:Key="Item.MouseOver.Border" Color="#a826A0Da"/>
<SolidColorBrush x:Key="Item.SelectedInactive.Background" Color="#3DDADADA"/>
<SolidColorBrush x:Key="Item.SelectedInactive.Border" Color="#FFDADADA"/>
<SolidColorBrush x:Key="Item.SelectedActive.Background" Color="#3D26A0DA"/>
<SolidColorBrush x:Key="Item.SelectedActive.Border" Color="#FF26A0DA"/>
<Style x:Key="ListBoxItemStyle1" TargetType="{x:Type ListBoxItem}">
    <Setter Property="SnapsToDevicePixels" Value="True"/>
    <Setter Property="Padding" Value="4,1"/>
    <Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
    <Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="BorderBrush" Value="Transparent"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
                    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                </Border>
                <ControlTemplate.Triggers>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsMouseOver" Value="True"/>
                        </MultiTrigger.Conditions>
                        <Setter Property="Background" TargetName="Bd" Value="{StaticResource Item.MouseOver.Background}"/>
                        <Setter Property="BorderBrush" TargetName="Bd" Value="{StaticResource Item.MouseOver.Border}"/>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="Selector.IsSelectionActive" Value="False"/>
                            <Condition Property="IsSelected" Value="True"/>
                        </MultiTrigger.Conditions>
                        <Setter Property="Background" TargetName="Bd" Value="{StaticResource Item.SelectedInactive.Background}"/>
                        <Setter Property="BorderBrush" TargetName="Bd" Value="{StaticResource Item.SelectedInactive.Border}"/>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="Selector.IsSelectionActive" Value="True"/>
                            <Condition Property="IsSelected" Value="True"/>
                        </MultiTrigger.Conditions>
                        <Setter Property="Background" TargetName="Bd" Value="{StaticResource Item.SelectedActive.Background}"/>
                        <Setter Property="BorderBrush" TargetName="Bd" Value="{StaticResource Item.SelectedActive.Border}"/>
                    </MultiTrigger>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="TextElement.Foreground" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Например, вы можете изменить ресурсы Co lor of Item.MouseOver.Background и Item.SelectedActive.Background.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...