Reputation: 20242
How to get Treeviewitem when I'll click at BTNAddProvince ?
In my case parent of button is stackpanel, and I can't get parent of stackpanel (is this good way to get node ?).
Any ideas ?
<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>
Upvotes: 0
Views: 2271
Reputation: 127
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;
}
Upvotes: 1
Reputation: 8392
You can get the TreeViewItem in this way:
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;
}
Upvotes: 1
Reputation: 17638
I would suggest you use a MVVM-based design for your TreeView (see http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx for a great article how to do this). Then bind your button to the ViewModel's command. That way you'll call the command on the ViewModel of the item, where you can then execute your specific logic based on the item.
Upvotes: 1