WPF ListBox Image Selected, сага продолжается

Хорошо, в моем ListBox прокручиваются изображения с текстом и т.д., сага продолжается. Когда я щелкаю один из элементов, чтобы выбрать его, запускается процесс открытия веб-браузера и перехода к определенному URL-адресу. Проблема, с которой я столкнулся сейчас, заключается в том, что, когда приложение WPF теряет фокус и открывается веб-браузер, элемент, щелкнувший внутри списка, становится белым. Вот весь список XAML ListBox. Я установил для выбранных элементов значение прозрачности, имеет ли это какое-то отношение к тому, что приложение WPF теряет фокус?

Есть ли что-то, что я могу добавить в код, запускающий процесс открытия веб-браузера, чтобы вернуть фокус приложению WPF?

Спасибо.

   <ListBox ItemsSource="{Binding Source={StaticResource WPFApparelCollection}}" Margin="61,-8,68,-18" ScrollViewer.VerticalScrollBarVisibility="Hidden" ScrollViewer.HorizontalScrollBarVisibility="Hidden" SelectionMode="Single" x:Name="list1" MouseLeave="List1_MouseLeave" MouseMove="List1_MouseMove" Style="{DynamicResource ListBoxStyle1}" Background="Transparent" BorderThickness="0">
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="Background" Value="Transparent" />
                <Setter Property="HorizontalContentAlignment" Value="{Binding Path=HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}" />
                <Setter Property="VerticalContentAlignment" Value="{Binding Path=VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}" />
                <Setter Property="Padding" Value="20,10,20,10" />
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type ListBoxItem}">
                            <Border x:Name="Bd" SnapsToDevicePixels="true" Background="Transparent" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}">
                                <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                            </Border>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsSelected" Value="true">
                                    <Setter Property="Background" TargetName="Bd" Value="Transparent" />
                                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}" />
                                </Trigger>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition Property="IsSelected" Value="true" />
                                        <Condition Property="Selector.IsSelectionActive" Value="false" />
                                    </MultiTrigger.Conditions>
                                    <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
                                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
                                </MultiTrigger>
                                <Trigger Property="IsEnabled" Value="false">
                                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListBox.ItemContainerStyle>
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel Orientation="Horizontal" IsItemsHost="True" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <Grid>
                        <Image Source="{Binding Image}" MouseLeave="Image_MouseLeave" MouseEnter="Image_MouseEnter" Cursor="Hand" Tag="{Binding Link}" MouseLeftButtonDown="Image_MouseLeftButtonDown"  VerticalAlignment="Top" HorizontalAlignment="Left"></Image>
                    </Grid>
                    <Label Content="{Binding Name}" Cursor="Hand" Tag="{Binding Link}" MouseLeftButtonDown="Label_MouseLeftButtonDown" VerticalAlignment="Bottom" Foreground="White" Style="{StaticResource Gotham-Medium}" FontSize="8pt" HorizontalAlignment="Center" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

person John Batdorf    schedule 23.12.2008    source источник


Ответы (1)


Одна уловка, которую я обнаружил, играя с цветами выделения в ListBox, - это работа с системными кистями, а не борьба с ними.

Когда ListBox находится в фокусе и выбран элемент, фон этого элемента - SystemColors.HighlightBrush. Однако, когда ListBox теряет фокус, фон выбранного элемента становится SystemColors.ControlBrush.

Зная это, вы можете переопределить системные кисти для этого ListBox, чтобы элементы внутри были окрашены в желаемые цвета.

<ListBox>
    <ListBox.Resources>
        <!-- override the system brushes so that selected items are transparent
             whether the ListBox has focus or not -->
        <SolidColorBrush
            x:Key="{x:Static SystemColors.HighlightBrushKey}" 
            Color="Transparent" />
        <SolidColorBrush
            x:Key="{x:Static SystemColors.ControlBrushKey}" 
            Color="Transparent" />
        <SolidColorBrush
            x:Key="{x:Static SystemColors.HighlightTextBrushKey}" 
            Color="Black" />
    </ListBox.Resources>
    <!-- ... your items here ... -->
</ListBox>
person Matt Hamilton    schedule 23.12.2008
comment
Вау ... ты, чувак. Здесь очень хорошая идея. Я должен начать думать о WPFish, а не о Webform / Winform. Еще раз спасибо. Джон - person John Batdorf; 23.12.2008
comment
Но если у вас есть контекстное меню в вашем ListBox, элементы в ContextMenu не будут выделены, верно? Как я могу добиться обоих вариантов поведения? - person jpsstavares; 20.07.2010
comment
@jpsstavares Да, ContextMenus технически не является частью того же визуального дерева, что и их владелец, поэтому кисти не будут унаследованы. Возможно, вам придется продублировать их в ресурсах ContextMenu, хотя я не пробовал. - person Matt Hamilton; 21.07.2010
comment
У меня было такое поведение, поэтому я переопределил HighlightBrushKey в ресурсах ContextMenu. - person jpsstavares; 21.07.2010