我有一个WPF的ComboBox
,它的IsEditable
属性绑定到一个视图模型上,可以进行开关控制。当它被打开时,我想要将焦点放在ComboBox
上,并选择编辑TextBox
中的所有文本。
我不知道最好的实现方式是什么。我应该替换ControlTemplate
,子类化ComboBox
基类并提供所需的属性,使用附加属性,还是采用其他方法?
#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时,它将注册侦听GotFocused事件并选择其中的所有文本。
使用方法很简单:
<ComboBox
IsEditable="True"
ComboBoxHelper:EditableComboBox.SelectWhenFocused="True"
x:Name="EditBox" />
<Button
Command="{Binding Focus}"
CommandParameter="{Binding ElementName=EditBox}"
Grid.Column="1" >Focus</Button>
public SimpleCommand Focus { get; set; }
public WindowVM()
{
Focus = new SimpleCommand {ExecuteDelegate = x => Broadcast(x as ComboBox)};
}
这是我实践过的一种经过验证的技术。希望它对您的问题不是一种过度解决方案。祝好运。
FindChild
方法。 - codekaizenPART_EditableTextBox
是什么? - BigeyesPART_EditableTextBox
是使用组合框的默认模板时可编辑文本框的名称。 - Tri Q Tran