WPF中确保显示ListBox选中的Item

本文介绍了一个自定义函数,用于确保WPF ListBox中选中的项始终保持在可视区域内。通过调整滚动条的位置,使得当前选中的项不会被滚动条隐藏。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

WPF中没有提供确保显示ListBox选中的Item这个功能,因此写了个函数来实现:

 

        public void EnsureListBoxItemVisible(ListBox listbox, ListBoxItem selectedItem)
        {

            int itemIndex = listbox.SelectedIndex;

            ScrollViewer scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(listbox, 0), 0);

            int verticalOffset = (int)scrollViewer.VerticalOffset;
            if (itemIndex < verticalOffset)
            {
                verticalOffset = itemIndex;
            }
            else if (itemIndex > (int)(scrollViewer.ViewportHeight + verticalOffset - 1))
            {
                verticalOffset = itemIndex + 1 - (int)scrollViewer.ViewportHeight;
            }

            if (verticalOffset != scrollViewer.VerticalOffset)
                scrollViewer.ScrollToVerticalOffset(verticalOffset);

        }

 

        private void TestListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Application.Current.Dispatcher.BeginInvoke(new Action(delegate
            {
                ListBoxItem selectedItem = e.OriginalSource as ListBoxItem;

                ViewModel.EnsureListBoxItemVisible(TestListBox, selectedItem);

            }), System.Windows.Threading.DispatcherPriority.ApplicationIdle);
        }

        private void TestListBox_ItemSelected(object sender, RoutedEventArgs e)
        {
            Application.Current.Dispatcher.BeginInvoke(new Action(delegate
            {
                ListBoxItem selectedItem = e.OriginalSource as ListBoxItem;

                ViewModel.EnsureListBoxItemVisible(TestListBox, selectedItem);

            }), System.Windows.Threading.DispatcherPriority.ApplicationIdle);
        }

 

          <ListBox x:Name="TestListBox" SelectionChanged="TestListBox_SelectionChanged">
            <ListBox.Resources>
              <Style TargetType="{x:Type ListBoxItem}">
                <EventSetter Event="ListBoxItem.Selected" Handler="TestListBox_ItemSelected" HandledEventsToo="True"/>
              </Style>
            </ListBox.Resources>
          </ListBox>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值