我正在尝试向控件添加一个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)
}
);
}
}该按钮被禁用(即使在设计模式下),并且不允许用户单击它。我刚刚实现了描述这里的代码。我哪里错了?
发布于 2018-10-22 06:42:58
正如@SirRufo在问题评论中所建议的那样,问题在于我为整个WPF窗口和另一个控件中的按钮声明了"CommandBindings“。
这种情况有两种解决方案:
1:为Button的直接父级声明CommandBindings。
2:为控件设置名称,该名称与命令绑定,并向控件添加如下代码:
<Window ... x:Name = "windowName" ...>
<Window.CommandBindings>
<CommandBinding Command="custumCommand:CustomCommands.Save" CanExecute ="CommandBinding_CanExecute" Executed="CommandBinding_Executed" />
</Window.CommandBindings>
<Grid>
<StackPanel>
<GroupBox>
<Button Command="custumCommand:CustomCommands.Save" CommandTarget = "{Binding ElementName=windowName}" Content="Save" />
</GroupBox>
</StackPanel>
</Grid>
</Window>查看Button的"CommandTarget“属性。
发布于 2018-10-21 14:27:52
由于下面的语句,您发布的代码会抛出一个错误,
<Window.CommandBindings>
<CommandBinding Command="local:CustomCommand.Save" CanExecute ="CommandBinding_CanExecute" Executed="CommandBinding_Executed" />
</Window.CommandBindings>在我把它改成下面之后,它开始对我起作用了,
<Window.CommandBindings>
<CommandBinding Command="local:CustomCommand.Save" CanExecute ="SaveCommand_CanExecute" Executed="SaveCommand_Executed" />
</Window.CommandBindings>代码隐藏中的事件处理程序不同于xaml for CommandBinding中的事件处理程序。
"SaveCommand_CanExecute“和"SaveCommand_Executed”
在进行上述更改后,它对我有效,当我点击它时,我可以看到带有“保存”消息的消息框。
希望你不会错过这个。如果有什么东西阻止了你,那就试着看看它是否进一步显示了错误,并让我们知道。
https://stackoverflow.com/questions/52914821
复制相似问题