我想在按下SHIFT键时改变按钮的文本(内容属性)。在这种情况下,按钮将执行不同的命令。这是一个常见的UI行为,例如在Photoshop中。
有什么办法可以做到这一点。
非常感谢
添加 KeyDown
或 PreviewKeyDown
事件到你的Button元素。
<Button Width="300" Height="50" Name="btnFunction" KeyDown="btnFunctionKeyDown" Content="Function1"/>
还有C#代码。
private void btnFunctionKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.LeftShift || e.Key == Key.RightShift)
{
btnFunction.Content = "Function2";
}
}
请看这篇文章以获取更多信息。
https:/docs.microsoft.comde-dedotnetapisystem.windows.input.keyboard.keydown?view=netcore-3.1。
这里是我的解决方案(事件在窗口处理)--非常感谢您的意见--如果有更好的解决方案,请评论......
internal void HandlePreviewKeyDown(KeyEventArgs e)
{
IInputElement focusedControl = FocusManager.GetFocusedElement(_window);
if (( (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift) && !(focusedControl?.GetType() == typeof(TextBox)))
{
// set button text
e.Handled = true;
}
}
internal void HandlePreviewKeyUp(KeyEventArgs e)
{
IInputElement focusedControl = FocusManager.GetFocusedElement(_window);
if ( (e.Key == Key.LeftShift) || (e.Key == Key.RightShift) && !(focusedControl?.GetType() == typeof(TextBox)))
{
// re-set button text
e.Handled = true;
}
}