考虑一下我有一个仅处理Messages
和Users
的应用程序,我希望我的窗口具有一个通用的Menu
和一个显示当前View
的区域。
我只能使用“消息”或“用户”,因此无法同时使用两个 View 。因此,我有以下控件
只是为了使其变得更简单,所以
Message Model
和User Model
都看起来像这样:现在,我有以下三个ViewModel:
UsersViewModel
和MessagesViewModel
都只是获取有关ObserverableCollection<T>
的Model
,该View
绑定(bind)在相应的<DataGrid ItemSource="{Binding ModelCollection}" />
中,如下所示:MainWindowViewModel
Commands
连接实现了ICommand
的两个不同的ViewModelBase
,它们看起来类似于以下内容:public class ShowMessagesCommand : ICommand
{
private ViewModelBase ViewModel { get; set; }
public ShowMessagesCommand (ViewModelBase viewModel)
{
ViewModel = viewModel;
}
public void Execute(object parameter)
{
var viewModel = new ProductsViewModel();
ViewModel.PartialViewModel = new MessageView { DataContext = viewModel };
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
}
还有另一种类似的会向用户显示。现在,此引入的
MainWindow.xaml
仅包含以下内容: public UIElement PartialViewModel
{
get { return (UIElement)GetValue(PartialViewModelProperty); }
set { SetValue(PartialViewModelProperty, value); }
}
public static readonly DependencyProperty PartialViewModelProperty =
DependencyProperty.Register("PartialViewModel", typeof(UIElement), typeof(ViewModelBase), new UIPropertyMetadata(null));
在
User Control
中使用此依赖项属性来动态显示<UserControl Content="{Binding PartialViewModel}" />
,如下所示:Window
此
PartialViewModel
上还有两个按钮可以触发命令:当这些被触发时,UserControl会更改,因为ojit_code是依赖项属性。
我想知道,如果这是不好的做法? 我不应该这样注入(inject)用户控件吗?还有另一种“更好的”替代方案与设计模式更好地对应吗?还是这是包括部分 View 的好方法?
最佳答案
为什么不在主窗口中将ContentPresenter/ContentControl与数据模板一起使用?
除了使用UserControl Content =“{Binding PartialViewModel}”/>,还可以使用:
<ContentPresenter Content="{Binding Path=PartialViewModel}" />
所有您需要做的:将PartialViewmodel设置为子viewmodel并创建一个数据模板,因此wpf将知道如何呈现childviewmodel
<DataTemplate DataType={x:Type UserViewModel}>
<UserView/>
</DataTemplate>
<DataTemplate DataType={x:Type MessageViewModel}>
<MessageView/>
</DataTemplate>
每当您在MainViewmodel中设置PartialViewmodel时,正确的View就会在您的ContenControl中呈现。
编辑1
至少您必须在ViewModel中实现INotifyPropertyChanged并在设置PartViewModel属性时将其触发。
编辑2
如果在 View 模型中使用Commands,请查看一些mvvm框架实现,例如DelegateCommand或RelayCommand。这样,处理ICommand变得容易得多。在您的mainviewmodel中,您可以创建像这样的简单命令
private DelegateCommand _showMessageCommand;
public ICommand ShowMessageCommand
{
get
{
return this._showMessageCommand ?? (this._showMessageCommand = new DelegateCommand(this.ShowMessageExecute, this.CanShowMessageExecute));
}
}
关于c# - 应用Mode-View-ViewModel设计模式时包括局部 View ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5229645/