WPF在Visualtree中获取ItemsItem控件 [英] WPF Get Item of Itemscontrol in Visualtree

查看:43
本文介绍了WPF在Visualtree中获取ItemsItem控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用附加属性为wpf实现DragAndDrop-manager.效果很好.但是只有一个问题.为了抓住被拖动的物品,我正在使用visualtree.作为示例,我想拥有listboxitem,但原始源是listboxitem的边框.因此,我只使用一种辅助方法来搜索具有ListBoxItem类型的父级.如果我发现它的数据并将其拖动.

I am implementing an DragAndDrop-manager for wpf using attached properties. It works quite nice. But there is only one problem. To grab the dragged item i am using the visualtree. As example I want to have the listboxitem but the originalsource is the border of the listboxitem. So I just use one of my helper methods to search for the parent with the type of ListBoxItem. If I found that I get the data of it and drag that.

但是我不想仅在使用列表框时使DragAndDrop-manager可用.不,我想在每个Itemscontrol上使用它. 但是一个DataGrid使用DataGridRows,一个listview使用ListViewItem ...那么,有没有机会一次又一次地不编写代码来获得该项?

But I dont want to have my DragAndDrop-manager aviable only while using a listbox. No I want to use it on every Itemscontrol. But a DataGrid uses DataGridRows, a listview uses ListViewItem... So is there any chance to get the item without writing the code again, again and again?

推荐答案

好,您可以使用此功能 (我更喜欢将其设置为静态):

well, you can have this function (i prefer to have it as static):

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                yield return (T)child;
            }

            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }
}

并使用这种方式:
即您想在yourDependencyObjectToSearchIn容器中找到所有TextBox元素

and use it some kind of this:
i.e. you want to find all TextBox elements in yourDependencyObjectToSearchIn container

foreach (TextBox txtChild in FindVisualChildren<TextBox>(yourDependencyObjectToSearchIn))
{
    // do whatever you want with child of type you were looking for
    // for example:
    txtChild.IsReadOnly = true;
}

如果您想让我为您提供一些解释,我将在起床后立即进行解释

if you want me to provide you some explanation, i'll do this as soon as i get up)

这篇关于WPF在Visualtree中获取ItemsItem控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆