2014-04-02 3 views
0

TreeViewItem의 treview 부모를 프로그래밍 방식으로 얻거나 WPF에서 예제를 돌려 볼 수 있는지 알고 싶습니다. 목표는 ViewModel에서 명령을 실행하기 위해 TreeView의 DataContext를 갖는 것입니다. 도움이 될 것입니다.TreeViewParent에서 TreeView 부모 가져 오기

여기에서 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

'명령'을 설정할 때 '바인딩'에 대해 '관련 소스'를 설정할 수 있습니다. XAML을 표시하여 treeview를 만드는 방법을 볼 수 있습니까? – Default

+0

답변 해 주셔서 감사합니다. XAML 코드를 추가했습니다. – TFFR

답변

1

사용하여 액세스 할 수 있습니다, 당신은 단지 ParentofType (treeviewItem)를 호출해야하고 그것은 당신에게 발견 한 최초의 트 리뷰를 줄 것이다 체인 또는 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; 
} 
+0

답변 해 주셔서 감사합니다. 나는 당신의 솔루션으로 내 문제를 해결했다. – TFFR

1

나는 this link을 확인합니다. 나는 코드 뒤에서 어떻게하는지 설명한다.

예에서 데이터 컨텍스트 내가 어떤 시점에서이 코드를 사용했다 parent.DataContext