在WPF中获取TreeViewItem

时间:2010-04-27 12:37:19

标签: c# wpf

当我点击BTNAddProvince时如何获取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>

3 个答案:

答案 0 :(得分:1)

我建议您为TreeView使用基于MVVM的设计(请参阅http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx以获取有关如何执行此操作的精彩文章)。然后将按钮绑定到ViewModel的命令。这样你就可以在项目的ViewModel上调用命令,然后你可以根据项目执行你的特定逻辑。

答案 1 :(得分: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;
}

答案 2 :(得分:1)