【问题标题】:Get the Treeview Parent From a TreeViewItem从 TreeViewItem 获取 Treeview 父级
【发布时间】:2014-04-02 11:29:33
【问题描述】:

我想知道是否有办法以编程方式获取 TreeViewItem 的treview 父级或 WPF 中的示例。 目标是拥有 TreeView 的 DataContext 以便执行来自 ViewModel 的命令。 任何帮助将不胜感激。

这里是 xaml 代码。 AddDisplayProperty 是树视图的数据上下文的一部分。 我的另一个问题是如何从 DataTemplate 的 TextBlock 中找到 TreeViewItem。

<TreeView ItemsSource="{Binding DisplayProperties, Mode=OneWay}" MinHeight="20" AllowDrop="True">
                        <i:Interaction.Behaviors>
                            <local:FrameworkElementCommandDropBehavior DropCommand="{Binding AddDisplayPropertyCommand}"  DropType="{x:Type local:SearchProperty}"/>
                        </i:Interaction.Behaviors>
                        <TreeView.Resources>
                            <DataTemplate DataType="{x:Type local:SearchProperty}">
                                <TextBlock Margin="5.0"  Text="{Binding Path=LongDescription, Mode=OneWay}" AllowDrop="True">
                                    <i:Interaction.Behaviors>
                                        <local:FrameworkElementCommandDropBehavior DropCommand="[Binding AddDisplayPropertyCommand}"  DropType="{x:Type local:SearchProperty}" DropParameters="{Binding}"/>
                                    </i:Interaction.Behaviors>
                                </TextBlock>
                            </DataTemplate>
                        </TreeView.Resources>
                    </TreeView>

【问题讨论】:

  • 您可以在设置Commands 时为您的Bindings 设置RelativeSource。您能否展示您的 XAML,以便我们了解您是如何创建树视图的?
  • 感谢您的回答。我已经添加了 XAML 代码。

标签: c# wpf


【解决方案1】:

我曾在某个时间点使用过此代码,您只需调用 ParentofType(treeviewItem),它就会为您提供找到链的第一个 Treeview 或 null。

public T ParentOfType<T>(DependencyObject element) where T : DependencyObject
{
    if (element == null)
    return default (T);
    else
    return Enumerable.FirstOrDefault<T>(Enumerable.OfType<T>((IEnumerable) GetParents(element)));
}

public IEnumerable<DependencyObject> GetParents( DependencyObject element)
{
    if (element == null)
        throw new ArgumentNullException("element");
    while ((element = GetParent(element)) != null)
        yield return element;
}

private DependencyObject GetParent(DependencyObject element)
{
    DependencyObject parent = VisualTreeHelper.GetParent(element);
    if (parent == null)
    {
        FrameworkElement frameworkElement = element as FrameworkElement;
        if (frameworkElement != null)
            parent = frameworkElement.Parent;
    }
    return parent;
}

【讨论】:

  • 感谢您的回答。我已经用你的解决方案解决了我的问题。
【解决方案2】:

我会查看this link。我认为它从后面的代码中解释了如何做到这一点。

可以使用 parent.DataContext 访问示例中的数据上下文

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 2011-07-10
    • 2016-09-06
    • 2011-08-23
    • 2021-10-15
    • 2020-11-13
    相关资源
    最近更新 更多