[英]WPF Get Item of Itemscontrol in Visualtree
我正在使用附加属性为wpf实现DragAndDrop-manager。 效果很好。 但是只有一个问题。 为了抓住被拖动的物品,我正在使用visualtree。 作为示例,我想拥有listboxitem,但原始源是listboxitem的边框。 因此,我只使用一种帮助方法来搜索具有ListBoxItem类型的父级。 如果我发现它的数据并将其拖动。
但我不想仅在使用列表框时使DragAndDrop-manager可用。 不,我想在每个Itemscontrol上使用它。 但是一个DataGrid使用DataGridRows,一个listview使用ListViewItem ...那么,有没有机会一次又一次地不编写代码来获得该项?
好吧,您可以拥有此功能(我更喜欢将其设为静态):
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元素
foreach (TextBox txtChild in FindVisualChildren<TextBox>(yourDependencyObjectToSearchIn))
{
// do whatever you want with child of type you were looking for
// for example:
txtChild.IsReadOnly = true;
}
如果您想让我为您提供一些解释,我将在起床后立即执行)
您可以使用FrameworkElement或UIElement来标识控件。
控制继承层次结构。
系统对象
System.Windows.Threading.DispatcherObject
System.Windows.DependencyObject
System.Windows.Media.Visual
System.Windows.UIElement
System.Windows.**FrameworkElement**
System.Windows.Controls.Control
System.Windows.Controls.ContentControl
System.Windows.Controls.ListBoxItem
System.Windows.Controls.**ListViewItem**
系统对象
System.Windows.Threading.DispatcherObject
System.Windows.DependencyObject
System.Windows.Media.Visual
System.Windows.UIElement
System.Windows.**FrameworkElement**
System.Windows.Controls.Control
System.Windows.Controls.**DataGridRow**
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.