I have a TextBox on an MVVM-designed UserControl. I should select all text in the TextBox if some conditions are fulfilled in the ViewModel and also check whether is all text selected.
I have searched a lot how could I implement it, and finally I have tried to use an attached property.
My attached property
public static class TextBoxExtension
{
public static readonly DependencyProperty IsSelectedAllProperty =
DependencyProperty.RegisterAttached
(
"IsSelectedAll",
typeof(bool?),
typeof(TextBoxExtension),
new FrameworkPropertyMetadata(IsSelectedAllChanged) { BindsTwoWayByDefault = true }
);
public static bool? GetIsSelectedAll(DependencyObject element)
{
if (element is null)
throw new ArgumentNullException("element");
return (bool?)element.GetValue(IsSelectedAllProperty);
}
public static void SetIsSelectedAll(DependencyObject element, bool? value)
{
if (element is null)
throw new ArgumentNullException("element");
element.SetValue(IsSelectedAllProperty, value);
}
private static void IsSelectedAllChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextBox textbox = (TextBox)d;
bool? oldValue = e.OldValue as bool?;
bool? newValue = e.NewValue as bool?;
if (oldValue is null)
{
textbox.GotFocus += SetIsSelectedAllProperty;
textbox.LostFocus += SetIsSelectedAllProperty;
textbox.SelectionChanged += SetIsSelectedAllProperty;
}
if (newValue == true)
{
textbox.Focus();
textbox.SelectAll();
}
}
private static void SetIsSelectedAllProperty(object sender, RoutedEventArgs e)
{
TextBox textBox = sender as TextBox;
textBox.SetValue
(
dp: IsSelectedAllProperty,
value:
textBox.IsFocused &&
textBox.SelectedText == textBox.Text
);
}
}
My textbox from the View:
<TextBox local:TextBoxExtension.IsSelectedAll="{Binding IsSelectedAll}"/>
It works perfectly in the most cases, but there is a problem when I am trying to select the text from the end to the begin of the text with mouse: when the selection reaches the 1st character the all selection is disappeared immediately.
Why is it happaning and how can I fix it? Please help!