Динамическое управление свойством IsItemClickEnable элемента GridView

1

Я заполнил gridview данными из списка на основе

 public class Players
    {
        public int id { get; set; }
        public string level { get; set; }
        public string image { get; set; }
        public List<string> name { get; set; }
    }

С помощью

 players = await Operations.GetPlayersAsync(Currentlevel); 
            ViewPlayers.ItemsSource = players;

Xaml GridView

<DataTemplate x:Key="ImageGalleryDataTemplate">
     <Border Background="#FF939598">
       <Image Margin="20,20,20,20" Source="{Binding image}" Height="250" Width="150" Stretch="Fill"/>
     </Border>
</DataTemplate>

<GridView x:Name="ViewPlayers" IsItemClickEnabled="True"  
          ItemTemplate="{StaticResource ImageGalleryDataTemplate}" SelectionMode="None" ItemClick="PlayerClick">
</GridView>

Grid View корректно загружает данные, и отображается весь элемент, и я могу щелкнуть их и выполнить необходимую задачу.

У меня есть база данных Sqllite, в которой хранятся данные формата

public class userData
    {[PrimaryKey, AutoIncrement]
        public int id { get; set; }

        public bool answered { get; set; }
      [Unique]  public string pid { get; set; }
        public string answer { get; set; }
    }

Я пытаюсь добиться того, чтобы отключить свойство IsItemClickEnabled для игроков (которое заполняется с помощью функции GetPlayersAsync), которое помечено как ответ (значение bool true). Я могу получить данные из данных Sqllite, сравнить и получить, какие все элементы будут отключены (ID игрока). Но я не могу отключить свойство IsItemClickEnabled конкретного игрока.

Я искал MSDN, Stackoverflow с возможными ключевыми словами, которые я могу, но не смог найти решение для динамического управления выбранными элементами в ItemsSource GridView или ItemView.

  • 0
    Было бы хорошо для вас, чтобы увидеть анимацию PointerPressed ? Если это не проблема, вы можете просто ничего не делать в ItemClicked -Eventhandler в зависимости от свойства ClickedItem в EventArgs .
  • 0
    Я мог бы справиться с анимацией PointerPressed , но все же я хочу манипулировать изображениями, ответы на которые есть в GridView, например, отображать их, указывая, что на них нельзя щелкнуть, или на них уже есть ответ, какое-либо решение?
Показать ещё 2 комментария
Теги:
xaml
gridview
windows-phone-8.1

1 ответ

0
Лучший ответ

Вы должны проверить, отвечает ли элемент в методе PlayerClick.

private void ListViewBase_OnItemClick(object sender, ItemClickEventArgs e)
{
    var item = e.ClickedItem as userData;
    if(item.answered) return;
    //continue process
}

Чтобы отключить визуальный эффект для ответного элемента, вы можете использовать ItemContainerStyleSelector

public class COntainerSelector : StyleSelector
{
    public Style Answered { get; set; }
    public Style Default { get; set; }
    protected override Style SelectStyleCore(object item, DependencyObject container)
    {
        var data = item as userData;
        //If data is null or it un answered we use default container (have tilt effect)
        if (data==null || !data.answered) return Default;

        return Answered;
        return base.SelectStyleCore(item, container);
    }
}

Контейнер предметов для un reply item (с эффектом наклона)

<Style x:Key="ContainerWithTiltEffect" TargetType="GridViewItem">
<Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
<Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="TabNavigation" Value="Local"/>
<Setter Property="IsHoldingEnabled" Value="False"/>
<Setter Property="Margin" Value="{ThemeResource GridViewItemMargin}"/>
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="GridViewItem">
            <Border x:Name="OuterContainer" RenderTransformOrigin="0.5,0.5">
                <Border.RenderTransform>
                    <ScaleTransform x:Name="ContentScaleTransform"/>
                </Border.RenderTransform>
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup x:Name="CommonStates">
                        <VisualStateGroup.Transitions>
                            <VisualTransition From="Pressed" To="Normal">
                                <Storyboard>
                                    <PointerUpThemeAnimation Storyboard.TargetName="TiltContainer"/>
                                </Storyboard>
                            </VisualTransition>
                        </VisualStateGroup.Transitions>
                        <VisualState x:Name="Normal"/>
                        <VisualState x:Name="Pressed">
                            <Storyboard>
                                <PointerDownThemeAnimation Storyboard.TargetName="TiltContainer"/>
                            </Storyboard>
                        </VisualState>
                        <VisualState x:Name="CheckboxPressed">
                            <Storyboard>
                                <PointerDownThemeAnimation Storyboard.TargetName="CheckboxTiltContainer"/>
                                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="NormalRectangle">
                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource CheckBoxPressedBackgroundThemeBrush}"/>
                                </ObjectAnimationUsingKeyFrames>
                                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="CheckGlyph">
                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource CheckBoxPressedForegroundThemeBrush}"/>
                                </ObjectAnimationUsingKeyFrames>
                            </Storyboard>
                        </VisualState>
                        <VisualState x:Name="Disabled">
                            <Storyboard>
                                <DoubleAnimation Duration="0" To="{ThemeResource ListViewItemDisabledThemeOpacity}" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="contentPresenter"/>
                                <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="Stroke" Storyboard.TargetName="NormalRectangle">
                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource CheckBoxDisabledBorderThemeBrush}"/>
                                </ObjectAnimationUsingKeyFrames>
                                <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="Fill" Storyboard.TargetName="CheckGlyph">
                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource CheckBoxDisabledForegroundThemeBrush}"/>
                                </ObjectAnimationUsingKeyFrames>
                                <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="SelectedBorder">
                                    <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
                                </ObjectAnimationUsingKeyFrames>
                                <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="Fill" Storyboard.TargetName="SelectedEarmark">
                                    <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
                                </ObjectAnimationUsingKeyFrames>
                                <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="Fill" Storyboard.TargetName="SelectedGlyph">
                                    <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
                                </ObjectAnimationUsingKeyFrames>
                            </Storyboard>
                        </VisualState>
                    </VisualStateGroup>
                    <VisualStateGroup x:Name="SelectionStates">
                        <VisualState x:Name="Unselected"/>
                        <VisualState x:Name="Selected">
                            <Storyboard>
                                <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="CheckGlyph"/>
                                <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="SelectedCheckMark"/>
                            </Storyboard>
                        </VisualState>
                        <VisualState x:Name="SelectedUnfocused">
                            <Storyboard>
                                <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="CheckGlyph"/>
                                <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="SelectedCheckMark"/>
                            </Storyboard>
                        </VisualState>
                    </VisualStateGroup>
                    <VisualStateGroup x:Name="DataVirtualizationStates">
                        <VisualState x:Name="DataAvailable"/>
                        <VisualState x:Name="DataPlaceholder">
                            <Storyboard>
                                <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="Visibility" Storyboard.TargetName="PlaceholderTextBlock">
                                    <DiscreteObjectKeyFrame KeyTime="0" Value="Visible"/>
                                </ObjectAnimationUsingKeyFrames>
                                <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="Visibility" Storyboard.TargetName="PlaceholderRect">
                                    <DiscreteObjectKeyFrame KeyTime="0" Value="Visible"/>
                                </ObjectAnimationUsingKeyFrames>
                            </Storyboard>
                        </VisualState>
                    </VisualStateGroup>
                    <VisualStateGroup x:Name="MultiSelectStates">
                        <VisualStateGroup.Transitions>
                            <VisualTransition From="ListMultiSelect" GeneratedDuration="0:0:0.15" To="NoMultiSelect"/>
                            <VisualTransition From="NoMultiSelect" GeneratedDuration="0:0:0.15" To="ListMultiSelect"/>
                        </VisualStateGroup.Transitions>
                        <VisualState x:Name="NoMultiSelect"/>
                        <VisualState x:Name="ListMultiSelect">
                            <Storyboard>
                                <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="X" Storyboard.TargetName="CheckboxContainerTranslateTransform"/>
                                <DoubleAnimation Duration="0" To="{ThemeResource ListViewItemContentTranslateX}" Storyboard.TargetProperty="X" Storyboard.TargetName="ContentBorderTranslateTransform"/>
                            </Storyboard>
                        </VisualState>
                        <VisualState x:Name="GridMultiSelect">
                            <Storyboard>
                                <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="SelectedBorder"/>
                            </Storyboard>
                        </VisualState>
                    </VisualStateGroup>
                    <VisualStateGroup x:Name="ReorderModeStates">
                        <VisualStateGroup.Transitions>
                            <VisualTransition From="ReorderEnabled" GeneratedDuration="00:00:00.2" To="ReorderDisabled"/>
                        </VisualStateGroup.Transitions>
                        <VisualState x:Name="ReorderEnabled">
                            <Storyboard>
                                <DropTargetItemThemeAnimation Storyboard.TargetName="OuterContainer"/>
                            </Storyboard>
                        </VisualState>
                        <VisualState x:Name="Reorderable">
                            <Storyboard>
                                <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="ScaleX" Storyboard.TargetName="ContentScaleTransform">
                                    <LinearDoubleKeyFrame KeyTime="00:00:00.075" Value="1.05"/>
                                    <LinearDoubleKeyFrame KeyTime="00:00:00.2" Value="1.0"/>
                                </DoubleAnimationUsingKeyFrames>
                                <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="ScaleY" Storyboard.TargetName="ContentScaleTransform">
                                    <LinearDoubleKeyFrame KeyTime="00:00:00.075" Value="1.05"/>
                                    <LinearDoubleKeyFrame KeyTime="00:00:00.2" Value="1.0"/>
                                </DoubleAnimationUsingKeyFrames>
                            </Storyboard>
                        </VisualState>
                        <VisualState x:Name="ReorderDisabled"/>
                    </VisualStateGroup>
                    <VisualStateGroup x:Name="ReorderHintStates">
                        <VisualStateGroup.Transitions>
                            <VisualTransition GeneratedDuration="0:0:0.2" To="NoReorderHint"/>
                        </VisualStateGroup.Transitions>
                        <VisualState x:Name="NoReorderHint"/>
                        <VisualState x:Name="BottomReorderHint">
                            <Storyboard>
                                <DragOverThemeAnimation Direction="Bottom" ToOffset="{ThemeResource ListViewItemReorderHintThemeOffset}" Storyboard.TargetName="ReorderHintContent"/>
                            </Storyboard>
                        </VisualState>
                        <VisualState x:Name="RightReorderHint">
                            <Storyboard>
                                <DragOverThemeAnimation Direction="Right" ToOffset="{ThemeResource ListViewItemReorderHintThemeOffset}" Storyboard.TargetName="ReorderHintContent"/>
                            </Storyboard>
                        </VisualState>
                        <VisualState x:Name="TopReorderHint">
                            <Storyboard>
                                <DragOverThemeAnimation Direction="Top" ToOffset="0" Storyboard.TargetName="ReorderHintContent"/>
                            </Storyboard>
                        </VisualState>
                        <VisualState x:Name="LeftReorderHint">
                            <Storyboard>
                                <DragOverThemeAnimation Direction="Left" ToOffset="0" Storyboard.TargetName="ReorderHintContent"/>
                            </Storyboard>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
                <Grid x:Name="ReorderHintContent" Background="Transparent">
                    <Border x:Name="CheckboxTiltContainer" HorizontalAlignment="Left" Margin="{ThemeResource ListViewItemMultiselectCheckBoxMargin}" VerticalAlignment="Top">
                        <Border x:Name="CheckboxOuterContainer">
                            <Border.Clip>
                                <RectangleGeometry Rect="0,0,25.5,25.5"/>
                            </Border.Clip>
                            <Grid x:Name="CheckboxContainer">
                                <Grid.RenderTransform>
                                    <TranslateTransform x:Name="CheckboxContainerTranslateTransform" X="{ThemeResource ListViewItemContentOffsetX}"/>
                                </Grid.RenderTransform>
                                <Rectangle x:Name="NormalRectangle" Fill="{ThemeResource CheckBoxBackgroundThemeBrush}" Height="25.5" Stroke="{ThemeResource CheckBoxBorderThemeBrush}" StrokeThickness="{ThemeResource CheckBoxBorderThemeThickness}" Width="25.5"/>
                                <Path x:Name="CheckGlyph" Data="M0,123 L39,93 L124,164 L256,18 L295,49 L124,240 z" Fill="{ThemeResource CheckBoxForegroundThemeBrush}" FlowDirection="LeftToRight" HorizontalAlignment="Center" Height="17" IsHitTestVisible="False" Opacity="0" Stretch="Fill" StrokeThickness="2.5" StrokeLineJoin="Round" VerticalAlignment="Center" Width="18.5"/>
                            </Grid>
                        </Border>
                    </Border>
                    <Border x:Name="ContentContainer">
                        <Border x:Name="TiltContainer">
                            <Border x:Name="ContentBorder" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}">
                                <Border.RenderTransform>
                                    <TranslateTransform x:Name="ContentBorderTranslateTransform"/>
                                </Border.RenderTransform>
                                <Grid>
                                    <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" ContentTransitions="{TemplateBinding ContentTransitions}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                                    <TextBlock x:Name="PlaceholderTextBlock" AutomationProperties.AccessibilityView="Raw" Foreground="{x:Null}" IsHitTestVisible="False" Margin="{TemplateBinding Padding}" Opacity="0" Text="Xg"/>
                                    <Rectangle x:Name="PlaceholderRect" Fill="{ThemeResource GridViewItemPlaceholderBackgroundThemeBrush}" IsHitTestVisible="False" Visibility="Collapsed"/>
                                </Grid>
                            </Border>
                        </Border>
                    </Border>
                    <Border x:Name="SelectedBorder" BorderBrush="{ThemeResource ListViewItemSelectedBackgroundThemeBrush}" BorderThickness="{ThemeResource GridViewItemMultiselectBorderThickness}" IsHitTestVisible="False" Opacity="0">
                        <Grid x:Name="SelectedCheckMark" HorizontalAlignment="Right" Height="34" Opacity="0" VerticalAlignment="Top" Width="34">
                            <Path x:Name="SelectedEarmark" Data="M0,0 L40,0 L40,40 z" Fill="{ThemeResource ListViewItemSelectedBackgroundThemeBrush}" Stretch="Fill"/>
                            <Path x:Name="SelectedGlyph" Data="M0,123 L39,93 L124,164 L256,18 L295,49 L124,240 z" Fill="{ThemeResource ListViewItemCheckThemeBrush}" FlowDirection="LeftToRight" HorizontalAlignment="Right" Height="14.5" Margin="0,1,1,0" Stretch="Fill" VerticalAlignment="Top" Width="17"/>
                        </Grid>
                    </Border>
                </Grid>
            </Border>
        </ControlTemplate>
    </Setter.Value>
</Setter>

для ответного элемента (Нет эффекта наклона): Скопируйте код выше, затем найдите и удалите эту строку и не забудьте изменить ключ "ContainerWithoutTiltEffect":

 <VisualStateGroup.Transitions>
   <VisualTransition From="Pressed" To="Normal">
      <Storyboard>
         <PointerUpThemeAnimation Storyboard.TargetName="TiltContainer"/>
      </Storyboard>
   </VisualTransition>
 </VisualStateGroup.Transitions>
 <VisualState x:Name="Normal"/>
 <VisualState x:Name="Pressed">
    <Storyboard>
       <PointerDownThemeAnimation Storyboard.TargetName="TiltContainer"/>
    </Storyboard>
 </VisualState>

Теперь объявите ItemContainerSelector:

<local:ContainerSelector x:Key="COntainerSelector" Default="{StaticResource ContainerWithTiltEffect}" Answered="{StaticResource ContainerWithoutTiltEffect}"/>

Используйте ItemContainerSelector в своем GridView

<GridView x:Name="ViewPlayers" IsItemClickEnabled="True" ItemTemplate="StaticResource ImageGalleryDataTemplate}" SelectionMode="None" ItemClick="PlayerClick" 
      ItemContainerStyleSelector="{StaticResource COntainerSelector}"/>
  • 0
    Я не пробовал этого, так как позже изменил логику своего проекта, например, позволил кликать, но представил прямоугольник поверх изображения серым цветом для показа, на который уже дан ответ. Я отмечу ваш ответ принятым, так как я думаю, что он будет работать нормально :) Еще раз спасибо

Ещё вопросы

Сообщество Overcoder
Наверх
Меню