WPF ListBox Изображение Выбранная сага продолжается - PullRequest
8 голосов
/ 23 декабря 2008

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

1 Ответ

36 голосов
/ 23 декабря 2008

Одна хитрость, которую я нашел, когда играл с выделенными цветами в 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>
...