前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >WPF桌面端开发2-ItemsControl和ListBox获取点击行的索引

WPF桌面端开发2-ItemsControl和ListBox获取点击行的索引

作者头像
码客说
发布2020-05-09 14:57:28
2.6K0
发布2020-05-09 14:57:28
举报
文章被收录于专栏:码客码客

前言

ItemsControl和ListBox都可以用做列表,既然是列表,那么我们怎样获取列表点击的项呢。

ListBox点击列表项后就不能再触发点击事件,而ItemsControl压根就没有选中项,那么怎样处理呢?

ListBox

自定义ListBox,当item选中后再重置为未选中

自定义ListBox

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace ZJClassTool.Views
{
    public class MyListBox : ListBox
    {
        protected override DependencyObject GetContainerForItemOverride()
        {
            return new MyListBoxItem();
        }

    }
    public class MyListBoxItem : ListBoxItem
    {
        protected override void OnSelected(System.Windows.RoutedEventArgs e)
        {
            DependencyObject dep = (DependencyObject)e.OriginalSource;
            while ((dep != null) && !(dep is ListBoxItem))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }

            if (dep == null) { return; }


            ListBoxItem item = (ListBoxItem)dep;
            if (item.IsSelected)
            {
                item.IsSelected = !item.IsSelected;
            }
            base.OnSelected(e);
        }
    }
}

使用

代码语言:javascript
复制
<views:MyListBox 
    x:Name="toolbar_list"
    ItemsSource="{Binding menuList}"
    ItemTemplate="{StaticResource ToolbarMenu}"
    SelectionChanged="myListBox_SelectionChanged"
    ScrollViewer.VerticalScrollBarVisibility="Disabled"
    ScrollViewer.HorizontalScrollBarVisibility="Disabled"
    Grid.Row="1" Background="#f3f3f3" BorderThickness="0">
</views:MyListBox>

对应的

代码语言:javascript
复制
private void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    object o = toolbar_list.SelectedItem;
    if (o == null)
    	return;
    MessageBox.Show(o.ToString());
}

ItemsControl

Item中添加Button,对Button添加事件,获取Button所在Item的Index

工具类

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;

namespace ZJClassTool.Utils
{
    class VTHelper
    {
        public static T FindChild<T>(DependencyObject parent, string childName)
   where T : DependencyObject
        {
            if (parent == null) return null;

            T foundChild = null;

            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                // 如果子控件不是需查找的控件类型
                T childType = child as T;
                if (childType == null)
                {
                    // 在下一级控件中递归查找
                    foundChild = FindChild<T>(child, childName);

                    // 找到控件就可以中断递归操作 
                    if (foundChild != null) break;
                }
                else if (!string.IsNullOrEmpty(childName))
                {
                    var frameworkElement = child as FrameworkElement;
                    // 如果控件名称符合参数条件
                    if (frameworkElement != null && frameworkElement.Name == childName)
                    {
                        foundChild = (T)child;
                        break;
                    }
                }
                else
                {
                    // 查找到了控件
                    foundChild = (T)child;
                    break;
                }
            }

            return foundChild;
        }

        public static List<T> FindChilds<T>(DependencyObject parent, string childName)
   where T : DependencyObject
        {
            var list = new List<T>();
            if (parent == null) return list;

            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                // 如果子控件不是需查找的控件类型
                T childType = child as T;
                if (childType == null)
                {
                    // 在下一级控件中递归查找
                    var findChildList = FindChilds<T>(child, childName);
                    for (int j = 0; j < findChildList.Count; j++)
                    {

                    }
                    list.AddRange(FindChilds<T>(child, childName));

                }
                else if (!string.IsNullOrEmpty(childName))
                {
                    var frameworkElement = child as FrameworkElement;
                    // 如果控件名称符合参数条件
                    if (frameworkElement != null && frameworkElement.Name == childName)
                    {
                        list.Add((T)child);
                    }
                }
                else
                {
                    // 查找到了控件
                    list.Add((T)child);
                }
            }

            return list;
        }

        /// <summary>
        /// 查找父元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static T FindParent<T>(DependencyObject i_dp) where T : DependencyObject
        {
            DependencyObject dobj = VisualTreeHelper.GetParent(i_dp);
            if (dobj != null)
            {
                if (dobj is T)
                {
                    return (T)dobj;
                }
                else
                {
                    dobj = FindParent<T>(dobj);
                    if (dobj != null && dobj is T)
                    {
                        return (T)dobj;
                    }
                }
            }
            return null;
        }
    }
}

xaml

代码语言:javascript
复制
<Window.Resources>
    <DataTemplate x:Key="ToolbarMenu">
        <Button x:Name="toolbar_item"  Background="Transparent" BorderThickness="0" Cursor="Hand" Height="60" Click="toolbar_item_Click">
            <Button.Content>
                <StackPanel Width="Auto" Background="Transparent">
                    <Image HorizontalAlignment="Center" Width="44" Source="{Binding Pic}"/>
                    <TextBlock HorizontalAlignment="Center" Text="{Binding Name}" Foreground="#3C525B"/>
                </StackPanel>
            </Button.Content>
        </Button>
    </DataTemplate>
</Window.Resources>
<ItemsControl 
    x:Name="toolbar_list"
    ItemsSource="{Binding menuList}"
    ItemTemplate="{StaticResource ToolbarMenu}"
    ScrollViewer.VerticalScrollBarVisibility="Disabled"
    ScrollViewer.HorizontalScrollBarVisibility="Disabled"
    Grid.Row="1" Background="#f3f3f3" BorderThickness="0">
</ItemsControl>

代码

代码语言:javascript
复制
private void toolbar_item_Click(object sender, RoutedEventArgs e)
{
    var clickindex = 0;
    var buttons = VTHelper.FindChilds<Button>(toolbar_list, "toolbar_item");
    for (var i = 0; i < buttons.Count; i++)
    {
        if (buttons[i] == sender)
        {
            clickindex = i;
            break;
        }
    }
}
本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-12-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • ListBox
  • ItemsControl
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com