我目前正试图了解Icommands的工作方式。我有一个示例项目。 https://github.com/alicanerdogan/HamburgerMenu只是为了玩,我在设置一个简单的点击事件时遇到了麻烦。
MainWindow.cs
public partial class MainWindow : Window, ICommand
{
public MainWindow()
{
InitializeComponent();
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
Dashboard dash = new Dashboard();
gridder.Children.Add(dash);
}
}
}
我知道执行运行我相信的代码。正如您所看到的,我只是将用户控件添加到网格中。在这种情况下,我无法理解如何添加多个单击事件或命令。 的 MenuItem.cs
public ICommand SelectionCommand
{
get { return (ICommand)GetValue(SelectionCommandProperty); }
set { SetValue(SelectionCommandProperty, value); }
}
public static readonly DependencyProperty SelectionCommandProperty =
DependencyProperty.Register("SelectionCommand", typeof(ICommand), typeof(SideMenuItem), new PropertyMetadata(null));
然后将其绑定到资源字典中的按钮。 的 MenuItem.xaml
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:SideMenuItem">
<Button x:Name="ListBoxItemButton" Command="{TemplateBinding SelectionCommand}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
我知道这可以作为模板使用,然后可以在窗口中使用。在mainWindow.xaml
我设置了菜单并加载正常,当按下一个项目时,执行执行方法。
的 MainWindow.xaml
<Local:SideMenu Background="#FFFF9203" MenuIconColor="White" SelectionIndicatorColor="White" MenuItemForeground="White" HorizontalAlignment="Left" >
<Local:SideMenu.Content>
<Local:SideMenuItem Icon="Images/home.png" Text="Home" SelectionCommand="{Binding ElementName=this_}" />
<Local:SideMenuItem Icon="Images/settings.png" Text="Settings" />
</Local:SideMenu.Content>
</Local:SideMenu>
因此,为了澄清后面的内容是如何为每个MenuItem分配不同的命令,这可能是严格的前进,但目前发现它令人困惑,为什么你会这样做,相比我认为是一个简单的按钮点击事件?