2014-04-02 50 views
0

我想知道是否有一种方法可以从一个TreeViewItem程序的马尔可夫或转换WPF中的示例。 目标是使TreeView的DataContext执行来自ViewModel的命令。 任何帮助,将不胜感激。从TreeViewItem获取树视图父亲

这里是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> 
+1

当你设置你的Command时,你可以为你的Binding设置'RelativeSource'。你可以展示你的XAML,以便我们看到你如何创建你的树视图? – Default

+0

感谢您的回答。我已经添加了XAML代码。 – TFFR

回答

1

我已经使用在某个时间点这个代码访问,你只需要调用ParentofType(树型视图),它会给你找到的第一个树形链或空。

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; 
} 
+0

感谢您的回答。我用你的解决方案解决了我的问题。 – TFFR

1

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

的例子在DataContext可以用parent.DataContext