2010-04-27 91 views
0

如何在我点击BTNAddProvince时获取Treeviewitem?在WPF中获取TreeViewItem

在我的情况下父按钮是stackpanel,我不能得到stackpanel的父(这是获得节点的好办法?)。

任何想法?

<HierarchicalDataTemplate DataType="{x:Type MyService:Region}" 
            ItemsSource="{Binding Path=ListOfProvinces}"> 
          <StackPanel Orientation="Horizontal"> 
           <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text="{Binding Path=Name}"/> 
        <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text=" H:"/> 
        <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text="{Binding Path=NumberOfHotels}"/> 
        <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text=" "/> 
        <Button Name="BTNAddProvince" Height="20" Content="+" Click="BTNAddProvince_Click"></Button> 
       </StackPanel> 
         </HierarchicalDataTemplate> 

回答

1

我会建议你使用基于MVVM的设计为您的TreeView(见http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx为一个伟大的文章如何做到这一点)。然后将您的按钮绑定到ViewModel的命令。这样你就可以在项目的ViewModel上调用这个命令,然后你可以根据这个项目执行你的特定逻辑。

1

您可以通过这种方式获得的TreeViewItem:

public New() 
{ 
    
    // This call is required by the designer. 
    InitializeComponent(); 
    
    _Items.Add(new Company { Name = "Company1", NumberOfHotels = 5 }); 
    _Items.Add(new Company { Name = "Company2", NumberOfHotels = 15 }); 
    _Items.Add(new Company { Name = "Company3", NumberOfHotels = 30 }); 
    
        
    tvItems.ItemsSource = _Items; 
} 

private void BTNAddProvince_Click(System.Object sender, System.Windows.RoutedEventArgs e) 
{ 
    
    Button button = sender as Button; 
    if (button == null) return;     
        
    TreeViewItem treeViewItem = GetVisualParent<TreeViewItem>(button); 
} 

public static T GetVisualParent<T>(Visual referencedVisual) where T : Visual 
{ 
    
    Visual parent = referencedVisual; 
    
    while (parent != null && !object.ReferenceEquals(parent.GetType, typeof(T))) { 
        parent = VisualTreeHelper.GetParent(parent) as Visual; 
    } 
    
    var parent1 = VisualTreeHelper.GetParent(referencedVisual); 
    
        
    return parent as T; 
} 
+0

object.ReferenceEquals(parent.GetType的typeof(T))< - 参数类型的方法组不分配给参数类型“对象' 并且你正在使用parent1? – user278618 2010-04-27 16:38:05

1
private void BTNAddProvince_Click(System.Object sender, System.Windows.RoutedEventArgs e) 
{  
    Button button = sender as Button; 
    Province p = button.DataContext as Province; 
    TreeViewItem item = treeView.ItemContainerGenerator.ContainerFromItem(p) as TreeViewItem;    
} 
+0

+1 treeView.ItemContainerGenerator.ContainerFromItem(p),正是我需要从绑定的数据项目中获取treeviewitem,谢谢。 – RobJohnson 2013-01-08 13:45:00

相关问题