1

我有一个针对关键时段 ( .) 的全局输入绑定。我仍然希望能够在TextBox? 有没有办法做到这一点?

这是一个简单的示例案例。当我在TextBox.

XAML:

<Window x:Class="UnrelatedTests.Case6.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
    <Window.InputBindings>
        <KeyBinding Key="OemPeriod" Command="{Binding Command}" />
    </Window.InputBindings>
    <Grid>
        <TextBox >Unable to type "." here!</TextBox>
    </Grid>
</Window>

C#:

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

namespace UnrelatedTests.Case6
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            DataContext = this;
        }

        public ICommand Command
        {
            get { return new CommandImpl(); }
        }


        private class CommandImpl : ICommand
        {
            public bool CanExecute(object parameter)
            {
                return true;
            }

            public void Execute(object parameter)
            {
                MessageBox.Show("executed!");
            }

            public event EventHandler CanExecuteChanged;
        }
    }
}
4

1 回答 1

2

您可以将其绑定并更改为Key您获得焦点时的值:KeyBindingKey.NoneTextBox

xml:

<Window x:Class="UnrelatedTests.Case6.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300"
        GotFocus="Window_GotFocus">
    <Window.InputBindings>
        <KeyBinding Key="{Binding MyKey}" Command="{Binding Command}" />
    </Window.InputBindings>
    <Grid>
        <TextBox/>
    </Grid>
</Window>

MainWindow.cs:(INotifyPropertyChanged实现

    Key _myKey;
    public Key MyKey
    {
        get
        {
            return _myKey;
        }
        set
        {
            _myKey = value;
            OnPropertyChanged("MyKey");
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        MyKey = Key.OemPeriod;
    }

    private void Window_GotFocus(object sender, RoutedEventArgs e)
    {
        if (e.OriginalSource is TextBox)
            MyKey = Key.None;
        else
            MyKey = Key.OemPeriod;
    }
于 2015-08-10T12:23:14.133 回答