我有一个带有TextBox和两个按钮的表单。一个按钮将IsDefault属性设置为true,将IsCancel设置为true以用于其他按钮。 TextBox是两个按钮的CommandTarget。当我按下TextBox上的Enter键或ESC键时,它按下相应的按钮就可以了。
我想从表单中删除按钮。它们不应该是可见的,但文本框应该像以前一样对Enter或ESC作出反应。我不能只将按钮的Visible属性设置为折叠 - 在这种情况下它们根本不起作用。我宁愿避免跟踪键盘事件。 有可能吗?
答案 0 :(得分:4)
虽然Skeets和Abe的方法有效,但他们 黑客攻击。您可以简单地指定也应该由所谓的InputGesture调用WPF命令,在这种情况下是KeyGesture(“enter”或“escape”)。您可以通过将命令的CommandBinding放在Visual Tree中的适当级别来设置此KeyGestures的范围。像这样:
<Window x:Class="CommandSpike.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CommandSpike"
Title="Window1" Height="300" Width="300">
<StackPanel>
<Grid>
<Grid.CommandBindings>
<CommandBinding x:Name="EnterBinding"
Command="{x:Static local:Commands.EnterCommand}"
CanExecute="CommandBinding_CanExecute"
Executed="EnterBinding_Executed"/>
<CommandBinding x:Name="CancelBinding"
Command="{x:Static local:Commands.CancelCommand}"
CanExecute="CommandBinding_CanExecute"
Executed="CancelBinding_Executed"/>
</Grid.CommandBindings>
<TextBox>
Press Enter or Cancel when I have focus...
</TextBox>
</Grid>
<TextBox Margin="0,4">
Pressing Enter or Cancel does nothing while I have focus!
</TextBox>
</StackPanel>
</Window>
using System.Windows;
using System.Windows.Input;
namespace CommandSpike
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void EnterBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Enter");
}
private void CancelBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Cancel");
}
}
}
using System.Windows.Input;
namespace CommandSpike
{
public static class Commands
{
public static RoutedUICommand EnterCommand { get;private set; }
public static RoutedUICommand CancelCommand { get; private set; }
static Commands()
{
EnterCommand=new RoutedUICommand("Enter",
"EnterCommand",
typeof(Commands));
EnterCommand.InputGestures.Add(
new KeyGesture(Key.Enter)
);
CancelCommand=new RoutedUICommand("Cancel",
"CancelCommand",
typeof(Commands));
CancelCommand.InputGestures.Add(
new KeyGesture(Key.Escape)
);
}
}
}
答案 1 :(得分:2)
您是否尝试过其他机制使按钮不可见?以下是一些建议:
答案 2 :(得分:1)
我会给他们一个空的ControlTemplate
:
<ControlTemplate x:Key="blankButton" TargetType="{x:Type Button}" />
...
<Button IsDefault="True" ... Template="{StaticResource blankButton}" />
<Button IsCancel="True" ... Template="{StaticResource blankButton}" />