我有一个解决方案给你。
我正在使用以下组合模型-视图-视图模型和附加属性方法。
首先,您需要了解消息传递MVVM 中的系统才能使其工作,并了解您的Commands。因此,从附加属性开始,我们开始为我们想要聚焦并选择所有文本的组合框设置 IsFocused 事件。
#region Select On Focus
public static bool GetSelectWhenFocused(DependencyObject obj)
{
return (bool)obj.GetValue(SelectWhenFocusedProperty);
}
public static void SetSelectWhenFocused(DependencyObject obj, bool value)
{
obj.SetValue(SelectWhenFocusedProperty, value);
}
// Using a DependencyProperty as the backing store for SelectWhenFocused. This enables animation, styling, binding, etc...
public static read-only DependencyProperty SelectWhenFocusedProperty =
DependencyProperty.RegisterAttached("SelectWhenFocused", typeof(bool), typeof(EditableComboBox), new UIPropertyMetadata(OnSelectOnFocusedChanged));
public static void OnSelectOnFocusedChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
bool SetProperty = (bool)args.NewValue;
var comboBox = obj as ComboBox;
if (comboBox == null) return;
if (SetProperty)
{
comboBox.GotFocus += GotFocused;
Messenger.Default.Register<ComboBox>(comboBox, Focus);
}
else
{
comboBox.GotFocus -= GotFocused;
Messenger.Default.Unregister<ComboBox>(comboBox, Focus);
}
}
public static void GotFocused(object sender, RoutedEventArgs e)
{
var comboBox = sender as ComboBox;
if(comboBox == null) return;
var textBox = comboBox.FindChild(typeof(TextBox), "PART_EditableTextBox") as TextBox;
if (textBox == null) return;
textBox.SelectAll();
}
public static void Focus(ComboBox comboBox)
{
if(comboBox == null) return;
comboBox.Focus();
}
#endregion
此代码显示的是当我们设置附加属性时SelectWhenFocused 为 true,它将注册监听获得焦点事件并选择里面的所有文本。
使用方法很简单:
<ComboBox
IsEditable="True"
ComboBoxHelper:EditableComboBox.SelectWhenFocused="True"
x:Name="EditBox" />
现在我们需要一个按钮,单击该按钮即可将焦点设置在组合框上。
<Button
Command="{Binding Focus}"
CommandParameter="{Binding ElementName=EditBox}"
Grid.Column="1" >Focus</Button>
请注意如何命令参数通过其名称 EditBox 绑定到 ComboBox。因此,当命令执行时,只有此 ComboBox 获得焦点并选择所有文本。
在我的 ViewModel 中,我有焦点命令声明如下:
public SimpleCommand Focus { get; set; }
public WindowVM()
{
Focus = new SimpleCommand {ExecuteDelegate = x => Broadcast(x as ComboBox)};
}
这是一项经过测试和验证的技术,对我有用。我希望这不是解决您问题的过度解决方案。祝你好运。