【问题标题】:How to move focus from AutoCompletBox after selecting an item?选择项目后如何从自动完成框移动焦点?
【发布时间】:2012-09-16 13:58:00
【问题描述】:

在我的应用程序中,用户可以将项目添加到ListBox。我希望用户能够在从AutoCompleteBox 中选择一个新项目后,通过再次按下 Return 键 来添加它。我认为将Add 按钮上的IsDefault 属性设置为True 就足够了。

MainWindow 代码如下所示:

<ListBox Name="listBox1" />

<Button Name="button1" Content="Add" IsDefault="True" Click="button1_Click" />

<my:AutoCompleteBox Name="autoCompleteBox1" 
                IsTextCompletionEnabled="True"
                PreviewKeyDown="autoCompleteBox1_PreviewKeyDown"/>

由于设置 IsDefault 不起作用,因为 AutoCompleteBox 为自己保持焦点,然后我尝试通过检查是否是 Return Key 来响应 KeyDown 事件按下并尝试将焦点设置到按钮。

但是在选择一个项目后按返回键并没有触发KeyDown 事件。所以我终于订阅了PreviewKeyDown 事件并这样做了:

public partial class MainWindow : Window
{
    ObservableCollection<string> myCollection = new ObservableCollection<string>();

    public MainWindow()
    {
        InitializeComponent();

        listBox1.ItemsSource = myCollection;
        autoCompleteBox1.ItemsSource = new string[] { "item1", "item2", "item3", "item4", "item5" };
    }

    private void autoCompleteBox1_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return)
        {
            button1.Focus(); 
        }
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        if (autoCompleteBox1.SelectedItem != null)
            myCollection.Add((string)autoCompleteBox1.SelectedItem);
    }
}

但是按钮没有获得焦点。如何将焦点从AutoCompleteBox 移开?

【问题讨论】:

  • 感谢@Blam 成功了。如何标记为答案?
  • 发表了我的评论作为答案。谢谢

标签: c# .net wpf wpftoolkit


【解决方案1】:

使用 KeyUp 事件。 KeyDown 在改变焦点的周期中为时过早。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多