zoukankan      html  css  js  c++  java
  • C# Note16: wpf window 中添加enter和双击事件

     一、添加回车(enter)事件

    在C#编程时,有时希望通过按回车键,控件焦点就会自动从一个控件跳转到下一个控件进行操作。

    以用户登录为例,当输入完用户名和密码后, 需要点击登录按钮,而登录按钮必须获得焦点, 一般的办法是用鼠标去点击就可以了。但是这样用户体验就会差一些(因为这样既要操作鼠标,又要操作键盘),其实可以实现按回车键就能自动获得下一个控件的焦点,这样直接用键盘输入就可以实现登录了,避免了鼠标的操作。常用的方法有两种:

    (1)在XAML中添加一条isdefalut属性为ture即可实现

    <Button x:Name="Enter_Btn" Content="Login" HorizontalAlignment="Left" Margin="280,49,0,0" VerticalAlignment="Top" Width="50" Height="50" Click="Enter_Btn_Click" IsDefault="True">
    

    (2)判断按键,跳转到指定控件 

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
          if (e.KeyCode == Keys.Enter)   //  if (e.KeyValue == 13) 判断是回车键
         {
               this.textBox2.Focus();
         }
    }

    (3)根据控件TabIndex 属性顺序跳转

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
         if (e.KeyCode == Keys.Enter)  
        {
              this.SelectNextControl(this.ActiveControl, true, true, true, true);  //需设置textBox的TabIndex顺序属性
         }
    }
    

      

    不过,以上三种方法在 AutoCompleteBox中都无效,经过研究,发现的解决方案:

    使用PreviewKeyDown

    private void InputRecipeName_PreviewKeyDown(object sender, KeyEventArgs e)
            {
                if (e.Key == Key.Enter)
                {
                    if (this.SaveBtn.Visibility == Visibility.Visible)
                    {
                        SaveBtn_Click(sender, e);
                    }
                    else
                    {
                        SelectBtn_Click(sender, e);
                    }
                }
            }
    

      

    PreviewKeyDown和KeyDown的区别?  

    二、添加双击事件

    双击listview中的item,直接触发点击按钮事件

    <Window.Resources>  
        <Style x:Key="itemstyle" TargetType="{x:Type ListViewItem}">  
            <EventSetter Event="MouseDoubleClick" Handler="HandleDoubleClick" />  
        </Style>  
    </Window.Resources>  
       
    <ListView Name="TrackListView" ItemContainerStyle="{StaticResource itemstyle}">  
    </ListView>  
      
    protected void HandleDoubleClick(object sender, MouseButtonEventArgs e)  
    {  
        if (this.SaveBtn.Visibility == Visibility.Visible)
       {
             SaveBtn_Click(sender, e);
       }
        else
       {
             SelectBtn_Click(sender, e);
       }
    }
    

      

      

    参考文献:

    WPF autocompletebox and the enter key

    AutoCompleteBox 类

  • 相关阅读:
    搭建微信小程序开发环境
    DOM 的classList 属性
    mui监听多个下拉刷新当前处于哪个选项卡
    mui常用功能链接地址
    css 弹性盒模型Flex 布局
    定义变量let,const
    微信小程序从零开始开发步骤(六)4种页面跳转的方法
    微信小程序从零开始开发步骤(五)轮播图
    展开符和解构赋值
    POJ 3660 Floyd传递闭包
  • 原文地址:https://www.cnblogs.com/carsonzhu/p/7286027.html
Copyright © 2011-2022 走看看