Помогите создать стиль для ListBoxItem - PullRequest
0 голосов
/ 17 марта 2009

Я новичок в стилях, и мне нужна помощь, чтобы создать стиль для ListBoxItem, который даст элементу прозрачный фон, а затем Font превратится в золото при наведении. Он не должен менять цвет при нажатии и возвращаться к нормальному состоянию, когда мышь отключается. Он по-прежнему должен передавать выбранный объект в событие PreviewMouseRightButtonDown для ListBox

В настоящее время я использую словарь по умолчанию из REUXABLES THEMES, но для этой части экрана в приложении это очень много раскраски.

Спасибо

    <DataTemplate x:Key="ItemsTemplate">
        <StackPanel Orientation="Vertical"
              Margin="0,5,0,5"
              Width="{Binding 
              Path=ActualWidth,
              RelativeSource={RelativeSource 
              Mode=FindAncestor, 
              AncestorType={x:Type ScrollContentPresenter}}}" MaxWidth="{Binding RelativeSource={RelativeSource FindAncestor, 
              AncestorType={x:Type ScrollViewer}}, Path=ViewportWidth}" >
            <TextBlock VerticalAlignment="Top" TextWrapping="Wrap" FontSize="14" Text="{Binding Path=CID}" />
                 <StackPanel Orientation="Horizontal" Margin="0,5,0,0" >
                    <TextBlock>
                        <Label Foreground="{DynamicResource DisabledForegroundBrush}" >Posted by</Label>
                        <Label Foreground="{DynamicResource DisabledForegroundBrush}" VerticalContentAlignment="Top" Content="{Binding Path=ACID}" />
                    </TextBlock>
                    <TextBlock>
                         <Label Foreground="{DynamicResource DisabledForegroundBrush}" Margin="3,0,0,0">at</Label>
                        <Label Foreground="{DynamicResource DisabledForegroundBrush}" Margin="3,0,3,0" VerticalContentAlignment="Top" Content="{Binding Path=Type}" />
                    </TextBlock>
                    <TextBlock>
                        <Label Foreground="{DynamicResource DisabledForegroundBrush}">(</Label>
                        <Label Foreground="{DynamicResource DisabledForegroundBrush}" VerticalContentAlignment="Top" Content="{Binding Path=Route}" />
                        <Label Foreground="{DynamicResource DisabledForegroundBrush}">)</Label>
                    </TextBlock>
                </StackPanel>

            </StackPanel>
    </DataTemplate>

    <Style x:Key="ItemsListBox" TargetType="{x:Type ListBoxItem}">
        <Setter Property="SnapsToDevicePixels" Value="true"/>
        <Setter Property="Background" Value="{DynamicResource Transparent}"/>
        <Setter Property="BorderBrush" Value="{DynamicResource Transparent}"/>
        <Setter Property="BorderBrush" Value="{DynamicResource Transparent}"/>
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
    </Style>

<ListBox x:Name="ListViewFlightPlans" Grid.Column="0" ItemTemplate="{DynamicResource ItemsTemplate}" 
                         MaxWidth="800" ScrollViewer.HorizontalScrollBarVisibility="Disabled" BorderBrush="Black" BorderThickness="2,0,0,1">

            </ListBox>

Dave

1 Ответ

1 голос
/ 17 марта 2009

К сожалению, изменение BorderBrush для ListBoxItem не даст желаемого эффекта, поскольку Border с выделением выделения является внутренним по отношению к ControlTemplate из ListBoxItem.

Вместо этого вы можете добавить новый ресурс Brush с ключом SystemColors.HighlightBrushKey , это ключ, который ListBoxItem использует для установки цвета выделения выделения.

Неактивная кисть выбора использует клавишу SystemColors.ControlBrushKey , поэтому, если вы переопределите оба из них с помощью прозрачного Brush, вы гарантированно не будете иметь никакого цвета выделения. Вы можете прочитать больше об этом в этой статье .

Вот пример со всем, кроме вашего DataTemplate:

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid.Resources>
        <x:Array x:Key="data" Type="{x:Type sys:String}">
            <sys:String>a </sys:String>
            <sys:String>bb</sys:String>
            <sys:String>ccc</sys:String>
            <sys:String>dddd</sys:String>
        </x:Array>
    </Grid.Resources>
    <ListBox ItemsSource="{StaticResource data}">
        <ListBox.Resources>
            <Style TargetType="{x:Type ListBoxItem}">
                <Style.Resources>
                    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
                    <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent"/>
                </Style.Resources>
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="Foreground" Value="Black"/>
                    </Trigger>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Foreground" Value="Gold"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ListBox.Resources>
    </ListBox>
</Grid>
...