WPF 中Menu自定义快捷键

前几天适用Menu控件,在使用自定义快捷键的时候遇到问题,现已解决,代码如下:

前台:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Window.CommandBindings>
        <CommandBinding Command="local:DataCommands.Requery" Executed="MenuItem_Click" />
    </Window.CommandBindings>
    <Grid>
        <Menu>
            <MenuItem Header="Tools">
                <MenuItem Header="_快捷键"  Command="local:DataCommands.Requery" />
            </MenuItem>
        </Menu>
    </Grid>
</Window>

后台:

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Requery");
        }

    }

    public class DataCommands
   
 {
       
  private static RoutedUICommand requery;
       
  static DataCommands()
       
  {
           
   InputGestureCollection inputs = new InputGestureCollection();
           
   inputs.Add(new KeyGesture(Key.G, ModifierKeys.Control, "Ctrl+G"));
           
   requery = new RoutedUICommand(
"Requery", "Requery", typeof(DataCommands), inputs);
       
  }
        
       
  public static RoutedUICommand Requery
       
  {
 get { return requery; }
 }
   
 }
}

注意前台引用命名空间

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WPF的时间选择框是使用DateTimePicker控件来实现的。但是,这个控件只能选择日期和时间,没有提供选择仅时间的选项。如果需要自定义时间选择框,可以使用WPF的ComboBox或者ListBox控件。 首先,我们需要创建一个ComboBox或者ListBox控件,并将其ItemsSource属性绑定到一个包含24小时的时间列表集合。例如: ``` <ListBox x:Name="timeListBox" ItemsSource="{Binding TimeList}"> ``` 其,TimeList是一个包含24小时时间的列表集合。接下来,我们需要为ListBox的ItemTemplate属性设置一个数据绑定,以便在列表框显示每个时间选项。例如: ``` <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding}" /> </DataTemplate> </ListBox.ItemTemplate> ``` 接下来,我们需要处理时间选择事件。当用户选择一个时间时,我们需要将选的时间值作为返回值返回给调用者。可以通过附加事件处理程序来实现时间选择事件的处理。例如: ``` private void TimeListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (timeListBox.SelectedItem != null) { string selectedTime = timeListBox.SelectedItem.ToString(); this.DialogResult = true; this.SelectedTime = selectedTime; this.Close(); } } ``` 在以上代码,我们首先检查用户是否选择了一个时间。如果用户没有选择任何项,则返回DialogResult为false。否则,我们将选的时间值保存在SelectedTime属性,并将返回DialogResult设置为true,然后关闭时间选择框。 最后,我们可以在时间选择框的代码实现一个公共属性SelectedTime,使得我们可以在调用时间选择框的代码获取到用户选的时间值。例如: ``` public string SelectedTime { get; set; } ``` 这样,我们就可以在WPF实现自定义的时间选择框了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值