我在MVVM设计的UserControl上有一个TextBox。如果在ViewModel中满足某些条件,则应在TextBox中选择所有文本,并检查是否选择了所有文本。
我进行了很多研究,我如何实现它,最后我尝试使用附加属性。
我的附属财产
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
);
}
}
“视图”中的我的文本框:
<TextBox local:TextBoxExtension.IsSelectedAll="{Binding IsSelectedAll}"/>
在大多数情况下它可以正常工作,但是当我尝试使用鼠标从文本的结尾到开头选择文本时出现了一个问题:当选择达到第一个字符时,所有选择立即消失。
为什么会发生这种情况,如何解决?请帮忙!