【发布时间】:2015-03-24 20:32:28
【问题描述】:
我创建了一个用户控件,里面有一个命令 (DeleteCommand):
public partial class TestControl : UserControl
{
public static RoutedCommand DeleteCommand = new RoutedCommand();
private void DeleteCommandExecute(object sender, ExecutedRoutedEventArgs e)
{
}
private void DeleteCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
public TestControl()
{
InitializeComponent();
CommandBinding deleteCommandBinding = new CommandBinding(DeleteCommand, DeleteCommandExecute, DeleteCommandCanExecute);
this.CommandBindings.Add(deleteCommandBinding);
}
}
我已经把这个 UserControl 放在了一个窗口中:
<Window x:Class="TestRoutedCommand.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestRoutedCommand"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Fire event" Margin="156,29,205,254" Command="{x:Static local:TestControl.DeleteCommand}" />
<local:TestControl Margin="126,135,135,46"/>
</Grid>
</Window>
还有一个使用 DeleteCommand 的按钮。我的问题是这个按钮总是被禁用并且永远不会调用 DeleteCommandCanExecute 处理程序,尽管 e.CanExecute 总是设置为 true。
我试过打电话:
CommandManager.InvalidateRequerySuggested();
但什么也没发生。该事件永远不会被触发。也许我做错了 CommandBinding。
我想要实现的是,当用户单击按钮时,DeleteCommandExecute 处理程序被触发。我的目标是为我的 MenuButtons 创建命令,这将触发我的 UserControls 中的一些方法,这些方法可能在 Visual Tree 的深处。
【问题讨论】:
-
如果您的命令是静态的,您是否尝试过将 DeleteCommandExecute 和 DeleteCommandCanExecute 也切换为静态?
-
尝试让 DeleteCommand 成为一个属性,而不仅仅是一个成员变量?
-
为什么用户控件中有命令?您通常会在视图模型中有一个命令,您可以在其中使用像 RelayCommand 这样的辅助类来实现它。