WPF MVVM 轻型菜单项单击“事件到命令”
本文关键字:命令 事件到命令 事件 MVVM 轻型 菜单项 单击 WPF | 更新日期: 2023-09-27 18:34:18
>我有以下问题。我已经为菜单和菜单项创建了一个用户控件:
用户控件以视图模型作为数据上下文启动,视图模型的构造函数触发并调用模型中的 ReylayCommand。当我单击视图中的菜单项时。然后什么也没发生。 我错过了什么?
我的 xaml:
<UserControl x:Class="TestDashBoard.Views.MenuItemView"
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:prop="clr-namespace:TestDashBoard.Properties"
xmlns:i="clr namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
mc:Ignorable="d" >
<Menu IsMainMenu="True">
<MenuItem Header="{x:Static prop:Resources.Setup}">
<MenuItem x:Name="salesSetup" Header="{x:Static prop:Resources.SaleSetup}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cmd:EventToCommand Command="{Binding SalesSetupClicked, Mode=OneWay}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</MenuItem>
</MenuItem>
</Menu>
</UserControl>
我的视图模型类:
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
namespace TestDashBoard.ViewModels
{
public class MenuItemViewModel : ViewModelBase
{
public RelayCommand SalesSetupClicked
{
get;
private set;
}
public RelayCommand InvtSetupClicked
{
get;
private set;
}
public MenuItemViewModel()
{
SalesSetupClicked = new RelayCommand(() =>
{
ShowSalesSetup();
});
InvtSetupClicked = new RelayCommand(() =>
{
ShowInvtSetup();
});
}
private void ShowSalesSetup()
{
}
private void ShowInvtSetup()
{
}
}
}
尝试在ViewModel中执行此操作:
使用 GalaSoft.MvvmLight;使用 GalaSoft.MvvmLight.Command;
namespace TestDashBoard.ViewModels
{
public class MenuItemViewModel : ViewModelBase
{
public RelayCommand _salesSetupClicked;
public RelayCommand SalesSetupClicked
{
get
{
if (_salesSetupClicked == null)
_salesSetupClicked = new RelayCommand(ShowSalesSetup);
return _salesSetupClicked;
};
private set;
}
public RelayCommand InvtSetupClicked
{
get;
private set;
}
public MenuItemViewModel()
{
SalesSetupClicked = new RelayCommand(() =>
{
ShowSalesSetup();
});
InvtSetupClicked = new RelayCommand(() =>
{
ShowInvtSetup();
});
}
private void ShowSalesSetup()
{
}
private void ShowInvtSetup()
{
}
}
}
尝试将您想要发生的代码放入构造函数中,而不是放入某个方法中。