【发布时间】:2019-03-25 16:06:35
【问题描述】:
我正在尝试将 WPF 自定义命令添加到控件。我做了什么:
XAML:
<Window x:Class="H.I.S.windows.CommandTest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:H.I.S.windows"
mc:Ignorable="d"
Title="CommandTest" Height="450" Width="800">
<Window.CommandBindings>
<CommandBinding Command="local:CustomCommand.Save" CanExecute ="SaveCommand_CanExecute" Executed="SaveCommand_Executed" />
</Window.CommandBindings>
<Grid>
<Button Command="local:CustomCommand.Save" Height="50" Width="100">Click me!</Button>
</Grid>
</Window>
C#:
namespace H.I.S.windows
{
public partial class CommandTest : Window
{
public CommandTest()
{
InitializeComponent();
}
private void SaveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void SaveCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Saved");
}
}
public static class CustomCommand
{
public static readonly RoutedUICommand Save = new RoutedUICommand(
"Save",
"Save",
typeof(CustomCommand),
new InputGestureCollection()
{
new KeyGesture(Key.F2)
}
);
}
}
按钮被禁用(即使在设计模式下)并且不允许用户点击它。 我刚刚实现了HERE 描述的代码。 我哪里错了?
【问题讨论】:
-
该按钮仅在设计模式下被禁用,但在运行时启用并工作。见github.com/SirRufo/so/tree/master/52914821/WpfApp1
-
@SirRufo 我试过你的解决方案和命令在运行时工作但我的不起作用
-
但它与您发布的 完全一样 - 检查 MainWindow xaml。如果它在您的 real 代码中不起作用,您没有向我们展示您的 real 代码
-
按钮必须在inside CommandBinding 的定义中(在您的示例中,您为整个窗口定义它)否则您必须为按钮设置 CommandTarget跨度>
-
我已经用一个测试命令和两个按钮更新了示例项目。由于设置了 CommandTarget,一个不工作,另一个工作