在WPF项目中找到控件 [英] Finding control within WPF itemscontrol

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

问题描述

我在itemsTemplate的datatemplate内只有几个文本框.当我将itemcontrols绑定到一个可观察的集合时,我得到两个文本框.但是我需要根据每个文本框进行一些操作,为此我想使用一些ID分别找到每个文本框.

Hi i have few a single textbox within the the datatemplate for itemscontrol. When i bind the itemcontrols to a observable collection i get two text boxes. But i need to do some manipulations based on each of the text boxes for which i want to find each textbox seperatly using some id.

任何人都可以在WPF中的项目控件中找到如何找到控件的帮助吗.

Can anybody help on how to find a control witin the itemscontrol in WPF.

推荐答案

使用ItemContainerGenerator,您可以获得项目的生成容器,并向下遍历可视树以找到您的TextBox.对于ItemsControl,它将是ContentPresenter,但是ListBox将返回ListBoxItem,ListView,ListViewItem等.

Using the ItemContainerGenerator you can obtain the generated container for an item and traverse the visual tree downwards to find your TextBox. In the case of an ItemsControl it will be a ContentPresenter, but a ListBox will return a ListBoxItem, ListView a ListViewItem, etc.

ContentPresenter cp = itemsControl.ItemContainerGenerator.ContainerFromItem(item) as ContentPresenter;
TextBox tb = FindVisualChild<TextBox>(cp);
if (tb != null)
{
    // do something with tb
}

public static T FindVisualChild<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)
            {
                return (T)child;
            }

            T childItem = FindVisualChild<T>(child);
            if (childItem != null) return childItem;
        }
    }
    return null;
}

如果需要,还可以通过使用索引获取容器

You can also obtain the container by index if you want by using

itemsControl.ItemContainerGenerator.ContainerFromIndex(0);

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

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