2013-11-21 2 views
2



Я пытаюсь создать шаблон ListBoxItem, который будет иметь закругленную границу при выборе. Я получил этот код XAML, который не работает по выбору:WPF Selected ListBoxItem с пользовательской границей

<ListBox x:Name="filtersListBox" Grid.Row="1" 
     Background="Transparent" BorderThickness="0" 
     ItemsSource="{Binding FilterItems}"> 
    <ListBox.ItemContainerStyle> 
     <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> 
    </ListBox.ItemContainerStyle> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Grid HorizontalAlignment="Center"> 
       <Border CornerRadius="8" BorderThickness="0" BorderBrush="Orange" 
         Margin="2" Background="Transparent" Name="itemBorder" 
         Width="275" VerticalAlignment="Center" 
         FocusManager.IsFocusScope="True" Focusable="True"> 
        <Border.Effect> 
         <DropShadowEffect BlurRadius="1" ShadowDepth="2" Color="DarkOrange" Opacity="0.3"/> 
        </Border.Effect> 
        <Border.Style> 
         <Style TargetType="Border"> 
          <Style.Triggers> 
           <Trigger Property="UIElement.IsFocused" Value="True"> 
            <Setter Property="Background" Value="Blue"/> 
           </Trigger> 
           <EventTrigger RoutedEvent="Border.MouseEnter"> 
            <BeginStoryboard> 
             <Storyboard> 
              <ThicknessAnimation Duration="0:0:0.25" 
                   To="2" 
                   Storyboard.TargetProperty="BorderThickness"/> 
             </Storyboard> 
            </BeginStoryboard> 
           </EventTrigger> 
           <EventTrigger RoutedEvent="Border.MouseLeave"> 
            <BeginStoryboard> 
             <Storyboard> 
              <ThicknessAnimation Duration="0:0:0.25" 
                   To="0" 
                   Storyboard.TargetProperty="BorderThickness"/> 
             </Storyboard> 
            </BeginStoryboard> 
           </EventTrigger> 
          </Style.Triggers> 
         </Style> 
        </Border.Style> 
        <TextBlock Text="{Binding Text}" Margin="10, 2"/> 
       </Border> 
      </Grid> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

Так что это ListBox, что я работаю.
События MouseEnter и MouseLeave, отлично работают!
Однако триггер UIElement.IsFocused не работает.

Любой совет будет очень благодарен! :)
Спасибо, Алекс.

ответ

1

Это так легко сделать, я очень удивлен, что никто не предложил этого еще. Либо укажите два DataTemplate s или два ControlTemplate s, один для стандартного вида и один для выбранного вида. Тогда просто добавьте этот Style (это первый пример использует DataTemplate ы):

<Style x:Key="SelectionStyle" TargetType="{x:Type ListBoxItem}"> 
    <Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}" /> 
    <Style.Triggers> 
     <Trigger Property="IsSelected" Value="True"> 
      <Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" /> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

Вы могли бы использовать его как это:

<ListBox ItemContainerStyle="{StaticResource SelectionStyle}" ... /> 

Вот другой пример с использованием двух ControlTemplate с (используется таким же образом,):

<Style x:Key="SelectionStyle" TargetType="{x:Type ListBoxItem}"> 
    <Setter Property="Template" value="{StaticResource DefaultTemplate}" /> 
    <Style.Triggers> 
     <Trigger Property="IsSelected" Value="True"> 
      <Setter Property="Template" value="{StaticResource SelectedTemplate}" /> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

Я оставлю вас, чтобы определить, что вы хотите, чтобы предметы выглядели так, как вы знаете, что лучше всего. Последнее примечание ... если вы используете этот метод (используя ControlTemplate s), убедитесь, что вы добавили ContentPresenter, чтобы содержимое элементов все равно отображалось. См., Например, страницу Control.Template Property на MSDN.

0

Вы пробовали настройку свойства Focusable на true. По умолчанию свойство false.

Посмотрите на эту ссылку:

http://msdn.microsoft.com/en-us/library/system.windows.uielement.focusable%28v=vs.110%29.aspx

Если это не помогает, то, возможно, этот подход будет соответствовать вам больше.

<ListBox.Resources> 
    <Style TargetType="{x:Type ListBoxItem}"> 
     <EventSetter Event="GotFocus" Handler="ListBoxItem_GotFocus"/> 
     <EventSetter Event="LostFocus" Handler="ListBoxItem_LostFocus"/> 
    </Style> 
</ListBox.Resources> 
0

Почему бы вам установить шаблон для ItemContainerStyle, то вы можете использовать триггер со свойством IsSelected = True. Смотрите код ниже:

<Window x:Class="WpfApplication7.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:system="clr-namespace:System;assembly=mscorlib" 
    xmlns:collections="clr-namespace:System.Collections;assembly=mscorlib" 
    Title="MainWindow" Height="350" Width="525"> 
<Window.Resources> 
    <collections:ArrayList x:Key="StringArray"> 
     <system:String>Hei</system:String> 
     <system:String>Hei</system:String> 
     <system:String>Hei</system:String> 
     <system:String>Hei</system:String> 
    </collections:ArrayList> 
</Window.Resources> 
<Grid> 
    <ListBox x:Name="filtersListBox" Grid.Row="1" 
    Background="Transparent" BorderThickness="0" 
    ItemsSource="{StaticResource StringArray}"> 
     <ListBox.ItemContainerStyle> 
      <Style TargetType="{x:Type ListBoxItem}"> 
       <Setter Property="Template"> 
        <Setter.Value> 
         <ControlTemplate TargetType="ListBoxItem"> 
          <Border CornerRadius="8" BorderThickness="0" BorderBrush="Orange" 
        Margin="2" Background="Transparent" Name="itemBorder" 
        Width="275" VerticalAlignment="Center" 
        FocusManager.IsFocusScope="True" Focusable="True"> 
           <Border.Effect> 
            <DropShadowEffect BlurRadius="1" ShadowDepth="2" Color="DarkOrange" Opacity="0.3"/> 
           </Border.Effect> 
           <ContentPresenter /> 
          </Border> 
            <ControlTemplate.Triggers> 
             <Trigger Property="IsSelected" Value="True"> 
              <Setter TargetName="itemBorder" Property="Background" Value="Blue"></Setter> 
             </Trigger> 
            </ControlTemplate.Triggers> 
         </ControlTemplate> 
        </Setter.Value> 
       </Setter> 
       <Style.Resources> 
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/> 
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent"/> 
       </Style.Resources> 
      </Style> 
     </ListBox.ItemContainerStyle> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <Grid HorizontalAlignment="Center"> 
        <Border CornerRadius="8" BorderThickness="0" BorderBrush="Orange" 
        Margin="2" Background="Transparent" Name="itemBorder" 
        Width="275" VerticalAlignment="Center" 
        FocusManager.IsFocusScope="True" Focusable="True"> 
         <Border.Effect> 
          <DropShadowEffect BlurRadius="1" ShadowDepth="2" Color="DarkOrange" Opacity="0.3"/> 
         </Border.Effect> 
         <Border.Style> 
          <Style TargetType="Border"> 
           <Style.Triggers> 
            <Trigger Property="UIElement.IsFocused" Value="True"> 
             <Setter Property="Background" Value="Blue"/> 
            </Trigger> 
            <EventTrigger RoutedEvent="Border.MouseEnter"> 
             <BeginStoryboard> 
              <Storyboard> 
               <ThicknessAnimation Duration="0:0:0.25" 
                  To="2" 
                  Storyboard.TargetProperty="BorderThickness"/> 
              </Storyboard> 
             </BeginStoryboard> 
            </EventTrigger> 
            <EventTrigger RoutedEvent="Border.MouseLeave"> 
             <BeginStoryboard> 
              <Storyboard> 
               <ThicknessAnimation Duration="0:0:0.25" 
                  To="0" 
                  Storyboard.TargetProperty="BorderThickness"/> 
              </Storyboard> 
             </BeginStoryboard> 
            </EventTrigger> 
           </Style.Triggers> 
          </Style> 
         </Border.Style> 
         <TextBlock Text="{Binding }" Margin="10, 2"/> 
        </Border> 
       </Grid> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
</Grid> 

Смежные вопросы