如果我创建一个 ViewModel 我需要以 MVVM 模式为它创建模型,这是真的吗?
例如,我的任务是在窗口顶部的 WPF 应用程序中创建简单菜单。
这是我的视图MainWindow.xaml
<Window x:Class="AppMvvm.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:AppMvvm.ViewModel"
Title="{Binding DisplayName}" Height="350" Width="525"
WindowStartupLocation="CenterScreen">
<Window.Resources>
<Style x:Key="MenuItemStyle">
<Setter Property="MenuItem.Command" Value="{Binding Command}" />
</Style>
<HierarchicalDataTemplate DataType="{x:Type vm:MenuItemViewModel}"
ItemsSource="{Binding Children}">
<ContentPresenter Content="{Binding DisplayName}" />
</HierarchicalDataTemplate>
</Window.Resources>
<DockPanel>
<DockPanel DockPanel.Dock="Top">
<Menu ItemsSource="{Binding MenuItems}" ItemContainerStyle="{StaticResource MenuItemStyle}"/>
</DockPanel>
</DockPanel>
</Window>
这是我的MenuItemViewModel.cs的ViewModel
namespace AppMvvm.ViewModel
{
public class MenuItemViewModel : ViewModelBase
{
public MenuItemViewModel(string menuItemName, IList<MenuItemViewModel> children)
{
base.DisplayName = menuItemName;
this.Children = children;
}
public MenuItemViewModel(string menuItemName)
: this (menuItemName, children: null)
{
}
public MenuItemViewModel(string menuItemName, ICommand command)
{
base.DisplayName = menuItemName;
this.Command = command;
}
public IList<MenuItemViewModel> Children { get; private set; }
public ICommand Command { get; private set; }
}
}
我的类WorkspaceViewModel.cs是绑定到视图的MainWindowViewModel.cs的基类
namespace AppMvvm.ViewModel
{
using Helpers;
public abstract class WorkspaceViewModel : ViewModelBase
{
#region Fields
private IList<MenuItemViewModel> _menuItems;
private RelayCommand _closeCommand;
#endregion
#region MenuItems
public IList<MenuItemViewModel> MenuItems
{
get
{
if (_menuItems == null)
_menuItems = CreateMenuItems();
return _menuItems;
}
}
List<MenuItemViewModel> CreateMenuItems()
{
return new List<MenuItemViewModel>
{
new MenuItemViewModel("File", CreateFileMenuItems()),
new MenuItemViewModel("Tools"),
new MenuItemViewModel("About")
};
}
#region CreateFileMenuItems & Commands
List<MenuItemViewModel> CreateFileMenuItems()
{
return new List<MenuItemViewModel>
{
new MenuItemViewModel("New"),
new MenuItemViewModel("Exit", CloseCommand)
};
}
public ICommand CloseCommand
{
get
{
if (_closeCommand == null)
_closeCommand = new RelayCommand(p => Close());
return _closeCommand;
}
}
void Close()
{
Application.Current.Shutdown();
}
#endregion
#endregion
}
}
以这种方式这样做是否正确,或者我需要为 MenuItemViewModel 类创建一个模型并以另一种方式进行?