gpt4 book ai didi

WPF:选择所有文本并将焦点设置到 ComboBox 的可编辑文本框

转载 作者:行者123 更新时间:2023-12-04 14:38:44 24 4
gpt4 key购买 nike

我有一个 WPF ComboBox,它的 IsEditable 属性绑定(bind)到一个可以打开和关闭它的 View 模型。当它打开时,我想将焦点放在 ComboBox 上并选择编辑 TextBox 中的所有文本。

我看不出最好的方法来完成这个。我应该替换 ControlTemplate,继承 ComboBox 基类,并提供所需的属性、使用附加属性或其他一些方法吗?

最佳答案

我有一个解决方案。

我正在使用 Model-View-ViewModel 和 Attached Property 方法的组合。

首先,您需要了解 MVVM 中的Messaging 系统才能正常工作,并了解您的命令。因此,从附加属性开始,我们开始将 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 时,它将注册以监听 GotFocused 事件 并选择其中的所有文本。

使用很简单:

<ComboBox
IsEditable="True"
ComboBoxHelper:EditableComboBox.SelectWhenFocused="True"
x:Name="EditBox" />

现在我们需要一个按钮,在单击时将焦点设置在 ComboBox 上。

<Button
Command="{Binding Focus}"
CommandParameter="{Binding ElementName=EditBox}"
Grid.Column="1" >Focus</Button>

请注意 CommandParameter 如何通过其名称 EditBox 绑定(bind)到 ComboBox。这样一来,当命令执行时,只有此 ComboBox 获得焦点并且所有文本都被选中。

在我的 ViewModel 中,我有如下声明的Focus 命令:

public SimpleCommand Focus { get; set; }
public WindowVM()
{
Focus = new SimpleCommand {ExecuteDelegate = x => Broadcast(x as ComboBox)};
}

这是一种经过测试和验证的技术,对我很有用。我希望这不是解决您问题的矫枉过正的方法。祝你好运。

关于WPF:选择所有文本并将焦点设置到 ComboBox 的可编辑文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2151285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com