1

is there an alternative to ItemContainerGenerator when working with a grouped LongListSelector?

I have a context menu on every ListBoxItem. One option is "delete item". This works fine with the following code (not really neat, but it works; better ways to implement?):

 private void deleteItem(object sender, RoutedEventArgs e)
    {
        ViewModel drink = (sender as FrameworkElement).DataContext as ViewModel;
        for (int i = 0; i < LLSGroups.Count; i++)
           {
              if (LLSGroups[i].Remove(drink))
              break;
           }
    }

I'd like to animate the item upon deletion. Therefore I need the FrameworkElement of that ListBoxItem. With a usual ListBox it works with

  FrameworkElement element = (MyList.ItemContainerGenerator.ContainerFromItem(((MenuItem)sender).DataContext) as ListBoxItem) as FrameworkElement; 

The Problem: LongListSelectors do not implement ItemContainerGenerator. How do I get the FrameworkElement for the animation?

Best Regards,

Marc

4

1 回答 1

1

我使用 VisualTreeHelper 构建了一个解决方法:输入由应该搜索的元素和我想找到的元素组成。

 private FrameworkElement SearchVisualTree(DependencyObject targetElement, DependencyObject comp)
    {
        FrameworkElement res = null;
        var count = VisualTreeHelper.GetChildrenCount(targetElement);
        if (count == 0)
            return res;

        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(targetElement, i);
            if ((child as FrameworkElement).DataContext == (comp as FrameworkElement).DataContext)
            {
                res = child as FrameworkElement;
                return res;
            }
            else
            {
                res = SearchVisualTree(child, comp);
                if (res != null)
                    return res;
            }
        }
        return res;
    }

调用如下所示:

FrameworkElement element = SearchVisualTree(myList, (sender as FrameworkElement));

这适用于对可视列表元素的操作 =)

于 2013-11-11T13:20:19.267 回答