I have tabItems with TextBox on their headers. I use LostFocus and MouseDoubleClick events to set the text to the TextBox.
<TabControl>
<TabItem Width="50">
<TabItem.Header>
<TextBox Text="text" IsReadOnly="True" LostFocus="TextBox_LostFocus" MouseDoubleClick="TextBox_MouseDoubleClick"/>
</TabItem.Header>
</TabItem>
</TabControl>
private void TextBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
TextBox text_box = sender as TextBox;
if (text_box == null) { return; }
text_box.IsReadOnly = false;
text_box.SelectAll();
}
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
TextBox text_box = sender as TextBox;
if (text_box == null) { return; }
text_box.IsReadOnly = true;
}
LostFocus event happens if only you click on the TabItem header area outside the TextBox or on enother TabItem. Clicking the tab item content area doesn't fire lost focus event.
How to make the TextBox to lose focus when user click any area outside the TextBox?
To lost Focus, in other word to get Focus at inside tab content(target):
Add event handler to PreviewMouseDown event(NOTE: NOT MouseDown) to react to mouse click. If you except 3 step, you application will react only to TAB key.
<TabControl>
<TabItem Width="50">
<TabItem.Header>
<TextBox
Text="text" IsReadOnly="True"
LostFocus="TextBox_LostFocus"
MouseDoubleClick="TextBox_MouseDoubleClick"/>
</TabItem.Header>
<Border Focusable="True" Background="Transparent" PreviewMouseDown="Border_PreviewMouseDown"/>
</TabItem>
</TabControl>
private void Border_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
var uiElement = sender as UIElement;
if (uiElement != null) uiElement.Focus();
}