I can't test this at the moment, but I think that it should work:
private void TreeView_Checked(object sender, RoutedEventArgs e)
{
CheckBox chkBox = sender as CheckBox;
StackPanel stackPanel = chkBox.Parent as StackPanel;
TextBlock txtBlock = FindVisualChild<TextBlock>(stackPanel);
Hyperlink hyperlink = FindVisualChild<Hyperlink>(stackPanel);
TextBlock secondTextBlock = FindVisualChild<TextBlock>(hyperlink);
bool isChecked = chkBox.IsChecked.HasValue ? chkBox.IsChecked.Value : false;
if (isChecked)
{
selectedNames.Add(txtBlock.Text);
selectedNames.Add(secondTextBlock.Text);
}
}
Let me know how it goes.
UPDATE >>>
Ok, so I wasn't sure whether that would work or not... it still looks like it should work, but I'll accept that you say it doesn't. So the only other way that I can think of you gaining access to that second TextBlock
would be to give it a name and use the FindName
method.
Rather than duplicate everything here, I'll point you towards the How to: Find DataTemplate-Generated Elements page on MSDN which features a detailed code example and explanation. In basic, you need to get the ContentPresenter
from the relevant TreeViewItem
and then you can access the DataTemplate
from the ContentPresenter
. Finally with the DataTemplate
, you can access the TextBlock
like this:
First change your XAML:
<Hyperlink NavigateUri="{Binding XPath=@WebSite}"
RequestNavigate="Hyperlink_RequestNavigate">
<TextBlock Name="SecondTextBlock" Text="{Binding XPath=@WebSite}" />
</Hyperlink>
Then get hold of the ContentPresenter
and use it like this:
TextBlock secondTextBlock = dataTemplate.
FindName("SecondTextBlock", contentPresenter) as TextBlock;
if (secondTextBlock != null) selectedNames.Add(secondTextBlock.Text );