在ItemsControl WPF中将焦点设置为一个项目

本文关键字:项目 一个 设置 WPF ItemsControl 焦点 | 更新日期: 2023-09-27 18:14:22

我在一个scrolviewer内水平显示图像列表,我使用下面的代码行来做它

<ScrollViewer Name="lviewThumbnails" Height="230"   >
<ItemsControl ItemsSource="{Binding ThumbsCollection}"  MouseWheel="ItemsControl_MouseWheel" > 
    <ItemsControl.ItemTemplate >
        <DataTemplate>
            <DockPanel Height="230">
                <Button Name="pageThumbnail" DockPanel.Dock="Top" Tag="{Binding}" VerticalAlignment="Top"  Margin="5,2">
                    <Grid>
                        <Image MaxWidth="140" Height="200" Source="{Binding ThubnailPath,IsAsync=True}" Stretch="None"></Image>                             
                    </Grid>
                </Button>
                <Label  HorizontalAlignment="Center"  FontSize="14" FontWeight="Bold" Content="text" Foreground="White" Padding="5"></Label>
            </DockPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel  Orientation="Horizontal"  />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

我想在打开视图时将焦点设置为此列表中的特定图像项例如,如果列表中有150张图片,我想在打开列表

时将焦点设置为图像75

我正在做的是点击按钮,我正在设置这个代码

  lviewThumbnails.Visibility = Visibility.Visible; 

使图像可见,但第一个项目是默认的每次选中的一个。我使用一个触发器来检测选中的图像,就像这样

  <DataTrigger Binding="{Binding IsSelected}" Value="True">                                            
                                        <Setter TargetName="pageThumbnail" Property="BorderBrush" Value="Yellow"/>
                                        <Setter TargetName="pageThumbnail" Property="BorderThickness" Value="3"/>
 </DataTrigger>

但问题是,如果图像75是选中的一个,我可以看到图像75周围的黄色边界,但焦点仍然在图像1上,当我点击按钮。我必须之前,下一个按钮的滚动查看器达到图像75。我正在使用特定样式的滚动查看器,如第1列按钮,第2列内容和第3列按钮(希望它不会影响默认行为),我正在防止鼠标滚动在滚动查看器上到处

 <ControlTemplate TargetType="{x:Type ScrollViewer}" x:Key="ButtonOnlyScrollViewer">
        <ControlTemplate.Resources>
        </ControlTemplate.Resources>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="20" />
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="20"/>
            </Grid.ColumnDefinitions>
            <Button Style="{StaticResource ResourceKey=ViewPreviousButton}" Grid.Column="0"   Command="ScrollBar.PageUpCommand" MouseWheel="ItemsControl_MouseWheel" 
                      Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"   HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></Button>
            <ScrollContentPresenter
            CanContentScroll="{TemplateBinding CanContentScroll}"
            Grid.Column="1" 
            Content="{TemplateBinding Content}"  
            Width="{TemplateBinding Width}"
            Height="{TemplateBinding Height}" 
            Margin="{TemplateBinding Margin}"/>
            <Button Style="{StaticResource ResourceKey=ViewNextButton}" Grid.Column="2"   Command="ScrollBar.PageDownCommand"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MouseWheel="ItemsControl_MouseWheel"
                     ></Button>
        </Grid>
    </ControlTemplate>

在ItemsControl WPF中将焦点设置为一个项目

所有这些答案都忽略了关于ItemsControls的关键信息。它们使用虚拟化,因此只有实际在视图中的项(以及一些周围的项)才是真正"存在"的。OP想要做的是不可能使用上面给出的答案,因为第75张图片实际上还不存在,所以你不能对它设置焦点。

你需要:

1)订阅ItemsControl ItemContainerGenerator。StatusChanged事件2)设置滚动位置,使第75个项目滚动到视图中3)在StatusChanged事件处理程序中,等待第75项的status = ContainerGenerated,然后取消订阅并设置焦点

是的,这太复杂了,是的,代码将"立即"执行,但是你必须等到容器生成后才能为第75项设置焦点。这就是虚拟化的工作原理。

当只创建了第1 - 10项时,您试图将焦点设置为第75项。

您可以使用附加属性FocusManager。FocusedElement

<DataTrigger Binding="{Binding IsSelected}" Value="True">                                            
    <Setter TargetName="pageThumbnail" Property="BorderBrush" Value="Yellow"/>
    <Setter TargetName="pageThumbnail" Property="BorderThickness" Value="3"/>
    <Setter TargetName="pageThumbnail" Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}"/>
</DataTrigger>

<DataTrigger Binding="{Binding IsSelected}" Value="True">                                            
    <Setter TargetName="pageThumbnail" Property="BorderBrush" Value="Yellow"/>
    <Setter TargetName="pageThumbnail" Property="BorderThickness" Value="3"/>
    <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=pageThumbnail}"/>
</DataTrigger>

如果上面没有正确聚焦,那么尝试先聚焦容器,然后聚焦pageThumbnail

<DataTrigger Binding="{Binding IsSelected}" Value="True">                                            
    <Setter TargetName="pageThumbnail" Property="BorderBrush" Value="Yellow"/>
    <Setter TargetName="pageThumbnail" Property="BorderThickness" Value="3"/>
    <Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}"/>
    <Setter TargetName="pageThumbnail" Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}"/>
</DataTrigger>

问题不仅在于焦点,还在于元素的位置,因为它在视图之外

try this xaml

<ItemsControl ItemsSource="{Binding ThumbsCollection}"  MouseWheel="ItemsControl_MouseWheel" Name="singleThumbs">
    <ItemsControl.Resources>
        <Style TargetType="ContentPresenter" xmlns:l="clr-namespace:WPFPerfomanceTest">
            <Setter Property="l:ScrollProvider.ScrollIntoView"
                    Value="{Binding IsSelected}" />
        </Style>
    </ItemsControl.Resources>
    <ItemsControl.ItemTemplate >
        <DataTemplate>
            <DockPanel Height="230">
                <Button Name="pageThumbnail"  DockPanel.Dock="Top" Tag="{Binding}" VerticalAlignment="Top"  Margin="5,2" Width="140">
                    <Grid>
                        <Image Height="200" Source="{Binding ThubnailPath,IsAsync=True}" Stretch="None"></Image>                                        
                    </Grid>
                </Button>
                <Label   HorizontalAlignment="Center"  FontSize="14" FontWeight="Bold" Content="{Binding PageNo}" Foreground="White" Padding="5"></Label>
            </DockPanel>
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding IsSelected}" Value="True" >
                    <Setter TargetName="pageThumbnail" Property="BorderBrush" Value="Yellow"/>
                    <Setter TargetName="pageThumbnail" Property="BorderThickness" Value="3"/>
                    <Setter TargetName="pageThumbnail" Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}"/>
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel  Orientation="Horizontal"  />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

注意,我已经为ContentPresenter和绑定ScrollProvider添加了样式。ScrollIntoView到IsSelected属性

还删除了图像的最大宽度,并为按钮指定width ="140"。最大宽度导致按钮大小缩小,直到图像被加载,这有效地取消了带入视图的行为

并使其正常工作

我们需要一些附加行为,将这个类添加到您的项目

class ScrollProvider : DependencyObject
{
    public static bool GetScrollIntoView(DependencyObject obj)
    {
        return (bool)obj.GetValue(ScrollIntoViewProperty);
    }
    public static void SetScrollIntoView(DependencyObject obj, bool value)
    {
        obj.SetValue(ScrollIntoViewProperty, value);
    }
    // Using a DependencyProperty as the backing store for ScrollIntoView.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ScrollIntoViewProperty =
        DependencyProperty.RegisterAttached("ScrollIntoView", typeof(bool), typeof(ScrollProvider), new PropertyMetadata(false, OnScrollIntoViewChanged));
    private static void OnScrollIntoViewChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        FrameworkElement element = d as FrameworkElement;
        if ((bool)e.NewValue)
        {
            element.BringIntoView();
            element.Focus();
        }
    }
}

您可以使用触发器来完成此操作,并为所选项目设置单独的模板或任何适合您的方式。

就像这样,假设你有image id作为属性;

<DataTrigger Binding="{Binding ThumbsCollection.ImageId}" Value="75">
   <Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" />
</DataTrigger>

如果你想设置焦点或显示一些效果,你可以绑定IsFocus并使用trigger

private void Button_Click(object sender, RoutedEventArgs e)
        {
            lviewThumbnails.Visibility = Visibility.Visible;
            int index = 75;
            ThumbsCollection[index].IsFocus = true;
            Button button = (Button)FindFirstVisualChild(lviewThumbnails, "pageThumbnail");
            lviewThumbnails.ScrollToHorizontalOffset((button.ActualWidth + 6.5) * index); // set it with pageThumbnail's location or margin
        }
        public object FindFirstVisualChild(DependencyObject obj, string childName)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child.GetValue(NameProperty).ToString() == childName)
                {
                    return child;
                }
                else
                {
                    object childOfChild = FindFirstVisualChild(child, childName);
                    if (childOfChild != null)
                    {
                        return childOfChild;
                    }
                }
            }
            return null;
        }

我认为你想在屏幕上显示第75项(中间项),所以你可以使用ScrollToHorizontalOffset。首先获取按钮的actualwith,然后在计算中获取它的margin/padding,然后你会得到offset

相关文章: