如何使用DataTemplate访问列表框中的特定项目?

如何使用DataTemplate访问列表框中的特定项目?,第1张

如何使用DataTemplate访问列表框中的特定项目?

谢谢您的帮助!!终于我明白了。使用VisualTreeHelper解决了该问题。多么出色的功能^^

private void ContactListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)    {        if (ContactListBox.SelectedIndex == -1) return;        currentSelectedListBoxItem = this.ContactListBox.ItemContainerGenerator.ContainerFromIndex(ContactListBox.SelectedIndex) as ListBoxItem;        if (currentSelectedListBoxItem == null) return;        // Iterate whole listbox tree and search for this items        TextBox nameBox = helperClass.FindDescendant<TextBox>(currentSelectedListBoxItem);        TextBlock nameBlock = helperClass.FindDescendant<TextBlock>(currentSelectedListBoxItem);

辅助功能

public T FindDescendant<T>(DependencyObject obj) where T : DependencyObject    {        // Check if this object is the specified type        if (obj is T) return obj as T;        // Check for children        int childrenCount = VisualTreeHelper.GetChildrenCount(obj);        if (childrenCount < 1) return null;        // First check all the children        for (int i = 0; i < childrenCount; i++)        { DependencyObject child = VisualTreeHelper.GetChild(obj, i); if (child is T)     return child as T;        }        // Then check the childrens children        for (int i = 0; i < childrenCount; i++)        { DependencyObject child = FindDescendant<T>(VisualTreeHelper.GetChild(obj, i)); if (child != null && child is T)     return child as T;        }        return null;    }


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5005402.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存