【问题标题】:get itemscontrol reference from item从项目中获取项目控制参考
【发布时间】:2012-03-08 22:36:36
【问题描述】:

我需要在几个 itemcontrols 之间拖动项目,每个项目都绑定到它自己的集合 当我拖动一个项目时,我需要知道它最初是从哪个项目控件中拖动的。

可拖动项目模板:

  <DataTemplate>
        <Ellipse MouseDown="Ellipse_MouseDown" ></Ellipse>
  </DataTemplate> 

项目控件:

  <ItemsControl Name="Pipe23" ItemsSource="{Binding Path=Pipes[23].Checkers}" ItemTemplate="{StaticResource PipeDataItem}"/>
  <ItemsControl Name="Pipe22" ItemsSource="{Binding Path=Pipes[22].Checkers}" ItemTemplate="{StaticResource PipeDataItem}"/>
  <ItemsControl Name="Pipe21" ItemsSource="{Binding Path=Pipes[21].Checkers}" ItemTemplate="{StaticResource PipeDataItem}"/>
  <ItemsControl Name="Pipe20" ItemsSource="{Binding Path=Pipes[20].Checkers}"  ItemTemplate="{StaticResource PipeDataItem}"/>

在 MouseDown 事件上拖动项目时,我可以引用被拖动的项目,但我也需要 引用从中拖出的 itemscontrol:如何做到这一点?

    private void Ellipse_MouseDown(object sender, MouseButtonEventArgs e)
    {
        Ellipse ellipse = (Ellipse)sender;
        Checker checker = (Checker)ellipse.DataContext;
        //  how do i reference the itemsconrtol containing the current ellipse (item)    
    }

【问题讨论】:

标签: wpf drag-and-drop


【解决方案1】:

我会向上导航 VisualTree,直到找到 ItemsControl 对象,这将是父对象。

我在我的博客上发布了一些 VisualTree helpers 这样做,我可以像这样使用它们来找到父 ItemsControl

private void Ellipse_MouseDown(object sender, MouseButtonEventArgs e)
{
    Ellipse ellipse = (Ellipse)sender;
    Checker checker = (Checker)ellipse.DataContext;

    ItemsControl parent = VisualTreeHelpers.FindAncestor<ItemsControl>(ellipse); 
}

【讨论】:

  • 只有一件事:VisualTreeHelper 没有 FindAncestor 我使用 VisualTreeHelper.GetParent(ellipse);它返回一个叫做 ContentPresenter 的东西
  • @eranotzer 在末尾添加s。在我意识到已经有一个名为VisualTreeHelper 的类之前,我将它称为VisualTreeHelpers。您还可以将类重命名为其他名称。
  • 我找不到这样的课程你确定不是msdn.microsoft.com/en-us/library/…
  • @eranotzer 要使用VisualTreeHelpers.FindAncestor&lt;T&gt;,您需要将我的博客文章中的代码添加到您的项目中(或创建您自己的)。这是一个带有一些自定义方法的自定义类,可以更轻松地导航 Visual Tree。
  • 必须有一个内置的方法来做这个谢谢我检查一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-21
相关资源
最近更新 更多