我怎么能在一个文本框中写一些'也用作键绑定
本文关键字:绑定 怎么能 文本 一个 | 更新日期: 2023-09-27 18:07:12
我有一个关键时期(.
)的全局输入绑定。我还想把它输入TextBox
吗?有办法做到这一点吗?
这里有一个简单的例子。
在"TextBox
"中输入period,执行该命令。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;
}
}
}
您可以绑定 KeyBinding
中的Key
,并在TextBox
获得焦点时将其值更改为Key.None
:
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"
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;
}