WPF - Retrieve Child DataTemplate Control From Custom ListBoxItem

不问归期 提交于 2019-12-08 03:54:40

There is no easy way for that. But knowing that you already came accross VisualTree stuff before maybe you have seen most of the codes in following example. And possibly what you missed is the first line, that shows you how to get ListBoxItem from CheckBoxItem. Having ListBoxItem on hand, means you have a DependencyObject to start using that VisualTree stuff technique to find RichTextBox :

var myListBoxItem = (lstTasks.ItemContainerGenerator.ContainerFromItem(lstTasks.Items[0]));

// Getting the ContentPresenter of myListBoxItem
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);

// Finding richtextbox from the DataTemplate that is set on that ContentPresenter
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
RichTextBox myTextBlock = (RichTextBox)myDataTemplate.FindName("rtbTask", myContentPresenter);

And implementation of FindVisualChild as shown in MSDN :

private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(obj, i);
        if (child != null && child is childItem)
            return (childItem)child;
        else
        {
            childItem childOfChild = FindVisualChild<childItem>(child);
            if (childOfChild != null)
                return childOfChild;
        }
    }
    return null;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!