相关文章推荐
冷冷的皮带  ·  ('IM004',"[IM004] ...·  1 年前    · 
满身肌肉的甜瓜  ·  Windows Server 2019 ...·  1 年前    · 
纯真的石榴  ·  Docker 的 8 ...·  1 年前    · 
自信的热水瓶  ·  could not convert ...·  1 年前    · 
备案 控制台
学习
实践
活动
专区
工具
TVP
写文章
专栏首页 码客 WPF桌面端开发2-ItemsControl和ListBox获取点击行的索引
3 0

海报分享

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

前言

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

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

ListBox

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

自定义ListBox

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);
}

使用

<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>

对应的

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

工具类

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;
                    // 查找到了控件
                    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);
                    // 查找到了控件
                    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;
                    dobj = FindParent<T>(dobj);
                    if (dobj != null && dobj is T)
                        return (T)dobj;
            return null;
}

xaml

<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>

代码

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;
}
本文参与 腾讯云自媒体分享计划 ,欢迎热爱写作的你一起参与!
本文分享自作者个人站点/博客: https://www.psvmc.cn 复制
如有侵权,请联系 cloudcommunity@tencent.com 删除。