WPF UserControl,包含按钮和键绑定

时间:2015-10-16 10:02:00

标签: c# wpf xaml user-controls key-bindings

我试图在WPF中实现拨号器。我有一个窗口,里面有一个用户控件。用户控件有很多按钮,但用户也可以使用数字键盘输入数字。

我创建了一个小型示例项目,以显示我在哪里:

MainWindow.xaml

<Window x:Class="wpf_dialer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:wpf_dialer"
        Title="MainWindow" Height="200" Width="525">
  <Window.Resources>
    <local:DialerViewModel x:Key="myViewModel" />
  </Window.Resources>
  <Grid DataContext="{StaticResource myViewModel}">
    <local:Dialer />
  </Grid>
</Window>

Dialer.xaml

<UserControl x:Class="wpf_dialer.Dialer"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:wpf_dialer"
             mc:Ignorable="d" 
             d:DesignHeight="200" d:DesignWidth="300"
             d:DataContext="{d:DesignInstance local:DialerViewModel}"
             Loaded="UserControl_Loaded">
  <UserControl.InputBindings>
    <KeyBinding Key="A" Command="{Binding CommandDialValue, Mode=OneTime}" CommandParameter="." />
    <KeyBinding Key="Back" Command="{Binding CommandDialValue, Mode=OneTime}" CommandParameter="Back" />
    <KeyBinding Key="Enter" Command="{Binding  CommandAcceptValue, Mode=OneTime}" CommandParameter="KeyBinding" />
  </UserControl.InputBindings>
  <UniformGrid Columns="1">
    <TextBox IsEnabled="False" Text="{Binding DialedValue, Mode=OneWay}" MinWidth="200" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10"/>
    <Button Content="OK" Margin="60,30" Command="{Binding CommandAcceptValue, Mode=OneTime}" CommandParameter="Button" />
  </UniformGrid>
</UserControl>

DialerViewModel.cs

using System;
using System.ComponentModel;
using System.Windows.Input;

namespace wpf_dialer
{
    class DialerViewModel : INotifyPropertyChanged
    {
        private Random RAND = new Random();
        private string _dialed_value = "00";
        public string DialedValue
        {
            get { return _dialed_value; }
            set
            {
                if (_dialed_value == value) return;
                _dialed_value = value;
                RaisePropertyChanged("DialedValue");
            }
        }

        public ICommand CommandDialValue { get { return new CommandImpl(DialValue); } }
        public ICommand CommandAcceptValue { get { return new CommandImpl(Alert); } }

        private void DialValue(object parameter)
        {
            if (parameter.ToString() == "Back")
            {
                if (DialedValue.Length > 0)
                {
                    DialedValue = DialedValue.Substring(0, DialedValue.Length - 1);
                }
            }
            else
            {
                DialedValue += RAND.Next(0, 10).ToString();
            }
        }

        private void Alert(object parameter)
        {
            System.Windows.MessageBox.Show(parameter.ToString());
        }

        #region INotifyPropertyChanged

        protected void RaisePropertyChanged(string property_name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property_name));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion

        private class CommandImpl : ICommand
        {
            private readonly Action<object> _action = null;
            public CommandImpl(Action<object> action)
            {
                _action = action;
            }

            public event EventHandler CanExecuteChanged;
            public bool CanExecute(object parameter) { return true; }
            public void Execute(object parameter) { _action(parameter); }
        }
    }
}

目的:

  • 加载窗口后,当用户按下A键时,会执行 CommandDialValue ;
  • 当用户按 Enter 时,会显示一个消息框,其中包含文本&#34; KeyBinding&#34;。必须从KeyBinding调用CommandAcceptValue,而不是从按钮调用;

问题:

  • 加载窗口时,KeyBindings不会执行。当我在UserControl中单击某个按钮时执行它们;

  • 当我按下Enter键时,会执行按钮的命令,但我希望执行用户控件的KeyBinding;

  • 此拨号程序必须保存在UserControl(或ControlTemplate或DataTemplate)中,因为它包含在一个非常复杂的窗口中。

  • 我不想将KeyBindings放在Window上,因为UserControl不可重复使用,因为它的DataContext与用户控件不同。

更新

我通过在所有按钮上设置Focusable="False"解决了第二个问题。

2 个答案:

答案 0 :(得分:2)

这是焦点问题。第一次加载窗口时,用户控件没有Focus。所以键绑定的手势不会拦截你的按键。在第一个应用加载时,您可以将Focus提供给您的用户控件。 (Focusable =“True”(我不知道这是否有帮助,但我确信FocusManager会有帮助))。然后你的关键手势将很好。

答案 1 :(得分:2)

为防止按钮获得焦点,我为所有按钮设置了Focusable="False"

要在窗口打开时设置焦点,我在UserControl上设置Focusable="True",在我调用Focus()的Loaded事件上设置。{/ p>

<强> Dialer.xaml

             d:DataContext="{d:DesignInstance local:DialerViewModel}"
             Loaded="UserControl_Loaded" Focusable="True">
  <UserControl.InputBindings>

<强> Dialer.xaml.cs

private void UserControl_Loaded(object sender, RoutedEventArgs e) {
    Focus();
}

我发现没有FocusManager.FocusedElement的组合可行。我尝试了{Binding ElementName=myUserControl}{Binding RelativeSource={RelativeSource Self}}

相关问题