This is an old question, but just had a similar problem to solve.
Since I remove my string format in my text as soon as I switch to the focus, the text is changed again after reaching the focus and TextBox.SelectAll becomes ineffective.
Therefore, I extended the solution I found here with the TextChanged event.
Here is my solution maybe it helps someone
My Text Box in a List
<GridViewColumn Header="{Binding HeaterSetpoint, Converter={StaticResource LocalizationGenericConverter}}" Width="80">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox x:Name="Setpoint" IsEnabled="{Binding SetpointEnable}" Width="50" TextAlignment="Right"
ToolTip="{Binding SetpointToolTip, Converter={StaticResource LocalizationGenericConverter}}"
behaviors:TextBoxBehavior.SelectAllTextOnFocus="True"
Focusable="True">
<b:Interaction.Behaviors>
<behaviors:TextBoxKeyDownBehavior />
</b:Interaction.Behaviors>
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="IsFocused" Value="true">
<Setter Property="Text" Value="{Binding Setpoint, UpdateSourceTrigger=LostFocus, Mode=TwoWay}" />
</Trigger>
</Style.Triggers>
<Setter Property="Text" Value="{Binding Setpoint, StringFormat={}0.## C°, UpdateSourceTrigger=LostFocus}" />
</Style>
</TextBox.Style>
</TextBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
My Text Box Behavior
public class TextBoxBehavior
{
public static bool GetSelectAllTextOnFocus(TextBox textBox)
{
return (bool)textBox.GetValue(SelectAllTextOnFocusProperty);
}
public static void SetSelectAllTextOnFocus(TextBox textBox, bool value)
{
textBox.SetValue(SelectAllTextOnFocusProperty, value);
}
public static readonly DependencyProperty SelectAllTextOnFocusProperty =
DependencyProperty.RegisterAttached(
"SelectAllTextOnFocus",
typeof(bool),
typeof(TextBoxBehavior),
new UIPropertyMetadata(false, OnSelectAllTextOnFocusChanged));
private static void OnSelectAllTextOnFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBox = d as TextBox;
if (textBox == null) return;
if (e.NewValue is bool == false) return;
if ((bool)e.NewValue)
{
textBox.GotFocus += SelectAll;
textBox.PreviewMouseDown += IgnoreMouseButton;
}
else
{
textBox.GotFocus -= SelectAll;
textBox.TextChanged -= SelectAllAfterChange;
textBox.PreviewMouseDown -= IgnoreMouseButton;
}
}
private static void SelectAll(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox == null) return;
textBox.Focus();
textBox.TextChanged += SelectAllAfterChange;
}
private static void SelectAllAfterChange(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox == null) return;
textBox.TextChanged -= SelectAllAfterChange;
textBox.SelectAll();
}
private static void IgnoreMouseButton(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null || textBox.IsKeyboardFocusWithin) return;
e.Handled = true;
textBox.Focus();
}
}