2014-10-10 8 views
1

У меня есть LongListSelector с GroupHeaderTemplate и ItemTemplate.Добавить выбранный эффект на LongListSelector с XAML

Я хочу добавить эффект «Избранное» для выбранного элемента в группе. Например, мой элемент под названием RightArrow может быть серым (теперь он синим).

Я пытался сделать это с помощью Expression Blend, но эффект не применим к выбранному элементу, но к каждому элементу.

Preview

<phone:LongListSelector x:Name="longListSelectorState" RenderTransformOrigin="-0.893,0.033" ItemTemplate="{StaticResource StateItemTemplate}" JumpListStyle="{StaticResource StateJumpListStyle}" LayoutMode="List" IsGroupingEnabled="true" HideEmptyGroups ="true" GroupHeaderTemplate="{StaticResource StateGroupHeaderTemplate}" Style="{StaticResource LongListSelectorStyle}"/> 

<Style x:Key="LongListSelectorStyle" TargetType="phone:LongListSelector"> 
    <Setter Property="Background" Value="Transparent"/> 
    <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="phone:LongListSelector"> 
       <Grid Background="{TemplateBinding Background}" d:DesignWidth="480" d:DesignHeight="800"> 
        <VisualStateManager.VisualStateGroups> 
         <VisualStateGroup x:Name="ScrollStates"> 
          <VisualStateGroup.Transitions> 
           <VisualTransition GeneratedDuration="00:00:00.5"/> 
          </VisualStateGroup.Transitions> 
          <VisualState x:Name="Scrolling"> 
           <Storyboard> 
            <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="VerticalScrollBar"/> 
           </Storyboard> 
          </VisualState> 
          <VisualState x:Name="Selected"> 
           <Storyboard> 
            <DoubleAnimation Duration="0" To="48" Storyboard.TargetProperty="(Control.FontSize)" 
              Storyboard.TargetName="textBlock" /> 

            <ColorAnimation Duration="0" To="Red" Storyboard.TargetProperty="(Control.Foreground).(SolidColorBrush.Color)" Storyboard.TargetName="textBlock" /> 
           </Storyboard> 
          </VisualState> 
          <VisualState x:Name="NotScrolling"/> 
         </VisualStateGroup> 
        </VisualStateManager.VisualStateGroups> 
        <Grid Margin="{TemplateBinding Padding}"> 
         <Grid.ColumnDefinitions> 
          <ColumnDefinition Width="*"/> 
          <ColumnDefinition Width="auto"/> 
         </Grid.ColumnDefinitions> 
         <ViewportControl x:Name="ViewportControl" HorizontalContentAlignment="Stretch" VerticalAlignment="Top"/> 
         <ScrollBar x:Name="VerticalScrollBar" Grid.Column="1" Margin="4,0,4,0" Opacity="0" Orientation="Vertical"/> 
        </Grid> 
       </Grid> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

<DataTemplate x:Key="StateItemTemplate"> 
    <StackPanel VerticalAlignment="Top"> 
     <Grid x:Name="grid"> 
      <StackPanel x:Name="stackPanel" Orientation="Vertical" HorizontalAlignment="Left"> 
       <TextBlock x:Name="textBlock" Text="{Binding ItemName}" Foreground="#DE000000" FontFamily="Segoe WP SemiLight" FontSize="29.333" Padding="0,5,0,0" Margin="4,0,0,0" /> 
       <TextBlock x:Name="textBlock1" Text="{Binding SubItemNames}" Visibility="{Binding HasSubItems, Converter={StaticResource BoolVisibilityConverter}}" Foreground="#DE000000" FontFamily="Segoe WP SemiLight" FontSize="21.333" Padding="0,4" LineHeight="2.667" /> 
      </StackPanel> 
      <Ellipse x:Name="RightArrow" Visibility="{Binding HasSubItems, Converter={StaticResource BoolVisibilityConverter}}" Fill="#FF0202EA" Stroke="Black" HorizontalAlignment="Right" Width="44" Height="44"/> 
     </Grid> 
    </StackPanel> 
</DataTemplate> 
+0

Также взгляните на это: http://stackoverflow.com/questions/18325889/how-to-highlight-a-selected-item-in-longlistselector – Kulasangar

ответ

1

Из того, что я вижу проблему в том, что вы подаете раскадровку на весь LongListSelector управления вместо одного элемента. Ваш VisualStateManager должен быть помещен в ItemTemplate (DataTemplate).

К несчастью, кажется, что из коробки нет крючков, поэтому вам необходимо вручную управлять своим состоянием товара с помощью метода VisualStateManager.GoToState.

Прежде всего, вы должны удалить раскадровку, назначенную состоянию Selected вашего LongListSelector, так как эта часть влияет на весь список.

Затем вы должны создать простое управление с двумя визуальными состояниями: Normal и Selected.

<UserControl x:Class="PhoneApp2.CustomLongListSelectorItem" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" 
    FontFamily="{StaticResource PhoneFontFamilyNormal}" 
    FontSize="{StaticResource PhoneFontSizeNormal}" 
    Foreground="{StaticResource PhoneForegroundBrush}" 
    d:DesignHeight="480" d:DesignWidth="480"> 

    <Grid x:Name="LayoutRoot"> 
     <VisualStateManager.VisualStateGroups> 
      <VisualStateGroup x:Name="CommonStates"> 
       <VisualState x:Name="Normal"/> 
       <VisualState x:Name="Selected"> 
        <Storyboard> 
         <ColorAnimation Duration="0" To="Red" 
             Storyboard.TargetProperty="(Control.Foreground).(SolidColorBrush.Color)" 
             Storyboard.TargetName="ContentTextBlock" /> 
        </Storyboard> 
       </VisualState> 
      </VisualStateGroup> 
     </VisualStateManager.VisualStateGroups> 

     <StackPanel Margin="12,12"> 
      <TextBlock x:Name="ContentTextBlock" Text="{Binding}" TextWrapping="Wrap"/> 
     </StackPanel> 
    </Grid> 
</UserControl> 

Затем добавить этот элемент управления для вашего DataTemplate, как показано ниже:

<phone:LongListSelector x:Name="ListSelector" SelectionChanged="HandleSelectionChanged"> 
    <phone:LongListSelector.ItemTemplate> 
     <DataTemplate> 
      <phoneApp2:CustomLongListSelectorItem/> 
     </DataTemplate> 
    </phone:LongListSelector.ItemTemplate> 
</phone:LongListSelector> 

И, наконец, вам придется добавить немного кода в код-позади вашей страницы, которая будет управлять состояния вашего таможенного контроля , В основном вам необходимо реализовать метод HandleSelectionChanged и GetItemsRecursive в качестве помощника, чтобы легко получить контроль над детьми.

private void HandleSelectionChanged(Object sender, SelectionChangedEventArgs e) 
{ 
    var userControlList = new List<CustomLongListSelectorItem>(); 
    GetItemsRecursive(ListSelector, ref userControlList); 

    // Selected. 
    if (e.AddedItems.Count > 0 && e.AddedItems[0] != null) 
    { 
     foreach (var userControl in userControlList) 
     { 
      if (e.AddedItems[0].Equals(userControl.DataContext)) 
      { 
       VisualStateManager.GoToState(userControl, "Selected", true); 
      } 
     } 
    } 

    // Unselected. 
    if (e.RemovedItems.Count > 0 && e.RemovedItems[0] != null) 
    { 
     foreach (var userControl in userControlList) 
     { 
      if (e.RemovedItems[0].Equals(userControl.DataContext)) 
      { 
       VisualStateManager.GoToState(userControl, "Normal", true); 
      } 
     } 
    } 
} 

public static void GetItemsRecursive<T>(DependencyObject parents, ref List<T> objectList) where T : DependencyObject 
{ 
    var childrenCount = VisualTreeHelper.GetChildrenCount(parents); 

    for (int i = 0; i < childrenCount; i++) 
    { 
     var child = VisualTreeHelper.GetChild(parents, i); 

     if (child is T) 
     { 
      objectList.Add(child as T); 
     } 

     GetItemsRecursive(child, ref objectList); 
    } 
} 

Приведенный выше код в основном из этого образца Highlight a selected item in the LongListSelector on WP8. Это может немного отличаться от образца, поскольку я хотел убедиться, что это будет работать правильно.

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