简体   繁体   English

WPF有没有办法在selectionchanged事件上获取项目的容器?

[英]WPF Is there a way to get the container for an item on a selectionchanged event?

Normally I would either search the visual tree or use the itemcontainergenerator to get the container. 通常我会搜索可视树或使用itemcontainergenerator来获取容器。 However, in wpf hierachicaldatatemplates have an itemcontainergenerator for each level, and it doesn't appear as if selectionchanged's event arguments contain the actual parent item or the container of the item. 但是,在wpf中,hierachicaldatatemplates为每个级别都有一个itemcontainergenerator,并且它看起来并不像selectionchanged的事件参数包含实际的父项或项的容器。

I can code around this by triggering on mousedown of an actual treeviewitem. 我可以通过触发实际的treeviewitem的moused来解决这个问题。 However, it seems odd that I can't use the selectionchanged event of the treeview to access the treeview's itemcontainers around the selected item. 但是,我不能使用treeview的selectionchanged事件来访问所选项目周围的treeview项目容器,这似乎很奇怪。

On the TreeView declaration: 在TreeView声明:

<TreeView Name="myTreeView" TreeViewItem.Selected="OnItemSelected"
ItemsSource="{Binding Source={StaticResource myHierarchicalData}}"/>

OnItemSelected handler: OnItemSelected处理程序:

private void OnItemSelected(object sender, RoutedEventArgs e)
{
    myTreeView.Tag = e.OriginalSource;
}

Here is the code to access TreeViewItem: 以下是访问TreeViewItem的代码:

if (myTreeView.SelectedItem != null)
{
    TreeViewItem selectedTVI = myTreeView.Tag as TreeViewItem;

    // add your code here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM