我有一个按钮作为每个ListViewItem的最后一列.按下按钮时,我需要在click事件中找到按钮(发件人)父列表视图项.
我试过了:
ListViewItem itemToCancel = (sender as System.Windows.Controls.Button).Parent as ListViewItem;
DiscoverableItem itemToCancel = (sender as System.Windows.Controls.Button).Parent as DiscoverableItem;
Run Code Online (Sandbox Code Playgroud)
DiscoverableItem是listview绑定的类型.我尝试了所有不同的组合,每个组合都返回null.
谢谢,梅森曼
Kin*_*ing 10
你可以VisualTreeHelper用来获得一些元素的祖先视觉效果.当然它只支持方法,GetParent但我们可以实现一些递归方法或类似的东西,然后走向树,直到找到所需的父类型:
public T GetAncestorOfType<T>(FrameworkElement child) where T : FrameworkElement
{
var parent = VisualTreeHelper.GetParent(child);
if (parent != null && !(parent is T))
return (T)GetAncestorOfType<T>((FrameworkElement)parent);
return (T) parent;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用这样的方法:
var itemToCancel = GetAncestorOfType<ListViewItem>(sender as Button);
//more check to be sure if it is not null
//otherwise there is surely not any ListViewItem parent of the Button
if(itemToCancel != null){
//...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2714 次 |
| 最近记录: |