2015-05-06 6 views
0

У меня есть объект ListView в универсальном проекте Windows. Я хочу установить два Visual States для выбранного и невыделенного состояния. Я скопировал код из MSDN:Visualstate Unselected not called

  <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="ListViewItem"> 
        <Border> 
         <VisualStateManager.VisualStateGroups> 
          <VisualStateGroup x:Name="CommonStates"> 
           <VisualState x:Name="Normal"> 

           </VisualState> 
           <VisualState x:Name="Disabled"/> 
           <VisualState x:Name="MouseOver"> 

           </VisualState> 
          </VisualStateGroup> 
          <VisualStateGroup x:Name="SelectionStates"> 
           <VisualState x:Name="Unselected"> 
            <Storyboard> 
             <ColorAnimation Duration="0:0:.1" To="{StaticResource HighlightColor}" Storyboard.TargetName="brd" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"> 
              <ColorAnimation.EasingFunction> 
               <PowerEase Power="2" /> 
              </ColorAnimation.EasingFunction> 
             </ColorAnimation> 
            </Storyboard> 
           </VisualState> 
           <VisualState x:Name="Selected"> 
            <Storyboard> 
             <ColorAnimation Duration="0:0:.1" To="{StaticResource FlowBlue}" Storyboard.TargetName="brd" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"> 
              <ColorAnimation.EasingFunction> 
               <PowerEase Power="2" /> 
              </ColorAnimation.EasingFunction> 
             </ColorAnimation> 
            </Storyboard> 
           </VisualState> 
          </VisualStateGroup> 
         </VisualStateManager.VisualStateGroups> 
         <Border Tapped="brd_Tapped" GotFocus="brd_GotFocus" Width="100" Height="85" Background="{StaticResource HighlightColorBrush}" BorderThickness="0" Name="brd" Tag="" Margin="5"> 
          <Grid Name="grd" Tag=""> 
           <TextBlock FontWeight="Bold" VerticalAlignment="Bottom" FontSize="18" HorizontalAlignment="Right" Foreground="{ThemeResource ApplicationPageBackgroundThemeBrush}" /> 
           <control:TextBoxEx LostFocus="TextBoxEx_LostFocus" IsHitTestVisible="True" DoubleTapped="TextBoxEx_DoubleTapped" Background="Transparent" Text="{Binding Path=ItemName, UpdateSourceTrigger=PropertyChanged}" TextWrapping="Wrap" Width="100" /> 
          </Grid> 
         </Border> 
        </Border> 
       </ControlTemplate> 
      </Setter.Value> 

Когда я бегу и нажимаю на элемент, вызывается состояние «Выбранное». Но когда я нажимаю на другой элемент, он также устанавливает состояние Selected. Но первый элемент не отменяет выбор. Я попытался установить SelectionMode в Single, но это не поможет. Что я могу сделать, чтобы снять элемент?

+0

Я думаю, что SelectionMode для ListBox и MultiSelect = «False» будет для ListView, если я правильно помню. –

+0

@ChrisW: Я попытался установить MultiSelect, но свойство больше не существует для ListView в Windows Universal. Я пробовал все варианты, но не использовал. – WJM

+0

Вам удалось решить эту проблему? В настоящее время потянув мои волосы за это -_- –

ответ

0

В части документации, предоставляемой для переноса приложений Win 8.1 в UWP, MSDN здесь документирует взломанные изменения в GridView. не

https://msdn.microsoft.com/en-us/library/windows/apps/mt188204.aspx#gridview

Все VisualStates в VisualStatesGroup 'SelectionStates' больше не поддерживается. Мне удалось обойти это, приняв использование ListViewItemPresenter в классе ControlTemplate.

Пожалуйста, обратитесь к стилю по умолчанию предлагается здесь: https://msdn.microsoft.com/en-us/library/windows/apps/mt299127.aspx

Ваш GridView.xaml должен выглядеть следующим образом;

<!-- Default style for Windows.UI.Xaml.Controls.GridViewItem --> 
 
<Style TargetType="GridViewItem"> 
 
    <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}" /> 
 
    <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}" /> 
 
    <Setter Property="Background" Value="Transparent"/> 
 
    <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}" /> 
 
    <Setter Property="TabNavigation" Value="Local"/> 
 
    <Setter Property="IsHoldingEnabled" Value="True"/> 
 
    <Setter Property="HorizontalContentAlignment" Value="Center"/> 
 
    <Setter Property="VerticalContentAlignment" Value="Center"/> 
 
    <Setter Property="Margin" Value="0,0,4,4"/> 
 
    <Setter Property="MinWidth" Value="{ThemeResource GridViewItemMinWidth}"/> 
 
    <Setter Property="MinHeight" Value="{ThemeResource GridViewItemMinHeight}"/> 
 
    <Setter Property="Template"> 
 
    <Setter.Value> 
 
     <ControlTemplate TargetType="GridViewItem"> 
 
     <ListViewItemPresenter 
 
      ContentTransitions="{TemplateBinding ContentTransitions}" 
 
      SelectionCheckMarkVisualEnabled="True" 
 
      CheckBrush="{ThemeResource SystemControlForegroundBaseMediumHighBrush}" 
 
      CheckBoxBrush="{ThemeResource SystemControlBackgroundChromeMediumBrush}" 
 
      DragBackground="{ThemeResource ListViewItemDragBackgroundThemeBrush}" 
 
      DragForeground="{ThemeResource ListViewItemDragForegroundThemeBrush}" 
 
      FocusBorderBrush="{ThemeResource SystemControlForegroundAltHighBrush}" 
 
      FocusSecondaryBorderBrush="{ThemeResource SystemControlForegroundBaseHighBrush}" 
 
      PlaceholderBackground="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" 
 
      PointerOverBackground="{ThemeResource SystemControlHighlightListLowBrush}" 
 
      PointerOverForeground="{ThemeResource SystemControlForegroundBaseHighBrush}" 
 
      SelectedBackground="{ThemeResource SystemControlHighlightAccentBrush}" 
 
      SelectedForeground="{ThemeResource SystemControlForegroundBaseHighBrush}" 
 
      SelectedPointerOverBackground="{ThemeResource SystemControlHighlightListAccentMediumBrush}" 
 
      PressedBackground="{ThemeResource SystemControlHighlightListMediumBrush}" 
 
      SelectedPressedBackground="{ThemeResource SystemControlHighlightListAccentHighBrush}" 
 
      DisabledOpacity="{ThemeResource ListViewItemDisabledThemeOpacity}" 
 
      DragOpacity="{ThemeResource ListViewItemDragThemeOpacity}" 
 
      ReorderHintOffset="{ThemeResource GridViewItemReorderHintThemeOffset}" 
 
      HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" 
 
      VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" 
 
      ContentMargin="{TemplateBinding Padding}" 
 
      CheckMode="Overlay"/> 
 
     </ControlTemplate> 
 
    </Setter.Value> 
 
    </Setter> 
 
</Style>

Надеется, что это помогает! :)

0

Сначала перетащите выделенное событие с измененным событием для элемента списка в коде позади. Попробуйте этот код в выбранном событии изменен. Надеюсь, это может вам помочь.

 if (e.AddedItems != null) 
    { 
     foreach (var item in e.AddedItems) 
     { 
      ListViewItem litem = (sender as ListView).ContainerFromItem(item) as ListViewItem; 
      if (litem != null) 
      { 
       VisualStateManager.GoToState(litem, "Unfocused", true); 
       VisualStateManager.GoToState(litem, "Normal", true); 
       VisualStateManager.GoToState(litem, "Selected", true); 
      } 
     } 
    } 
    if (e.RemovedItems != null) 
    { 
     foreach (var item in e.RemovedItems) 
     { 
      ListViewItem litem = (sender as ListView).ContainerFromItem(item) as ListViewItem; 
      if (litem != null) 
      { 
       VisualStateManager.GoToState(litem, "Unselected", true); 
      } 
     }