Thanks for a nice question. I think there could be several solutions for that. One solution could be to find the Visual Parent in the Code behind and then select the treeViewitem. So What i have done is given below,
The XAML Code,
<StackPanel>
<TreeView>
<TreeView.Resources>
<Style TargetType="TreeViewItem">
<Setter Property="Padding" Value="5"/>
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<TextBox Text="{Binding Mode=OneWay}" IsKeyboardFocusedChanged="TextBox_IsKeyboardFocusedChanged"/>
</DataTemplate>
</Setter.Value>
</Setter>
<!--<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="IsSelected" Value="True"/>
</Trigger>
</Style.Triggers>-->
</Style>
</TreeView.Resources>
<TreeViewItem Header="One">
<TreeViewItem Header="ChildOne"/>
</TreeViewItem>
<TreeViewItem Header="One">
<TreeViewItem Header="ChildOne"/>
</TreeViewItem>
<TreeViewItem Header="One">
<TreeViewItem Header="ChildOne"/>
</TreeViewItem>
</TreeView>
<TreeView>
<TreeViewItem Header="One">
<TreeViewItem Header="ChildOne"/>
</TreeViewItem>
<TreeViewItem Header="One">
<TreeViewItem Header="ChildOne"/>
</TreeViewItem>
<TreeViewItem Header="One">
<TreeViewItem Header="ChildOne"/>
</TreeViewItem>
</TreeView>
</StackPanel>
And in the code behind you need to write some code,
private void TextBox_IsKeyboardFocusedChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (Convert.ToBoolean(e.NewValue) == true)
{
var v = FindVisualParent<TreeViewItem>(sender as UIElement);
v.IsSelected = true;
}
}
public static T FindVisualParent<T>(UIElement element) where T : UIElement
{
UIElement parent = element; while (parent != null)
{
T correctlyTyped = parent as T; if (correctlyTyped != null)
{
return correctlyTyped;
}
parent = VisualTreeHelper.GetParent(parent) as UIElement;
} return null;
}
That's all. Enjoy it.