【发布时间】:2019-07-14 07:32:37
【问题描述】:
我想将两个快捷方式绑定到我的代码后面的功能。
但这两个函数永远不会被调用。
我有以下实现:
Fitst NavigationWindow 被调用,它的源属性如下:Source="MainPage.xaml"
MainPage.xaml 代码:
<Page x:Class="XXX.MainPage"
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:XXX"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="MainPage" DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<RoutedUICommand x:Key="Ctr1" Text="Another Text" />
<RoutedUICommand x:Key="Ctr2" Text="Another Text" />
</ResourceDictionary>
</Page.Resources>
<Page.InputBindings>
<KeyBinding Key="F10" Modifiers="Ctrl" Command="{StaticResource Ctr1}" />
<KeyBinding Key="F12" Modifiers="Ctrl" Command="{StaticResource Ctr2}" />
</Page.InputBindings>
<Page.CommandBindings>
<CommandBinding Command="{StaticResource Ctr1}" Executed="CtrShortcut1" />
<CommandBinding Command="{StaticResource Ctr2}" Executed="CtrShortcut2" />
</Page.CommandBindings>
<Grid/>
</Page>
MainPage.xaml.cs 代码:
public MainPage()
{
InitializeComponent();
this.DataContext = this;
}
public void CtrShortcut1(Object sender, ExecutedRoutedEventArgs e)
{
FONCTIONS.ShowToast("success", "test");
}
public void CtrShortcut2(Object sender, ExecutedRoutedEventArgs e)
{
FONCTIONS.ShowToast("success", "test2");
}
我做错了什么?
这甚至可以在页面上绑定快捷方式吗?
编辑
xaml 代码:
<Page.InputBindings>
<KeyBinding Key="F12" Command="{Binding DoSomething}"/>
</Page.InputBindings>
xaml.cs 代码:
public ICommand DoSomething { get; set; }
private void doSomething(object obj)
{
FONCTIONS.ShowToast("success", "Shortcut work !");
}
public MainPage()
{
InitializeComponent();
this.DataContext = this;
DoSomething = new RelayCommand(doSomething);
}
解决方案 我找不到从 Controls.Page 调用快捷方式的方法 但它适用于 NavigationWindow 和 Window。 为了获取页面的上下文,我在静态变量中对当前页面进行引用,然后调用 StaticVariable.Foo()
页面代码:
public static dynamic CurrentPage;
public MainPage()
{
InitializeComponent();
this.DataContext = this;
FONCTIONS.CurrentPage = this;
}
在我的 MainWindow 代码中:
private void CurrentPageSetup1(object obj)
{
REF_TO_STATIC_CLASS.CurrentPage.OpenSetup();
}
【问题讨论】:
-
你为什么不直接实现一个 icommand 与你的键绑定一起工作?
-
我没有找到 icommand/keybindings 实现的工作示例
标签: c# wpf keyboard-shortcuts