I have created a tab control and Created the tabItems dynamically, but i dont know how to add controls into the tabItems using MVVM. Could any one help me
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
You Dont have to add controls you just have to specify the UserControl.
TabControl has two properties
ItemTemplate
&&Content Template
ItemTemplate is for how the
Tab
will look where asContentTemplate is how the Tab Content will Look... so...
Xaml for the above
There are a few ways to programmatically add Tab Items in
WPF
and I am going to show you a simple example on how I deal with this in my application.First I host a collection of the
ViewModels
for theTabItems
(orWorkspaces
as I refer to them) in myMainWindowViewModel.cs
:Next I add a reference to the various controls in my
MainWindow.xaml
. This is important as we want to make sure that whenever the collection contains aViewModel
that it displays the appropriateView
for that Model.If you have multiple types of UserControls you simply add them all here like this:
Next we add the
TabControl
and bind it to ourWorkspace
Collection.Then I simply add my
ViewModels
to the Collection to have them show up in theTabControl
.My
WorkspaceViewModel
that I base theTabItem
collection of is very simple and looks something like this:Adding a TabItem:
To create a
TabItem
you simply create aUserControl
andViewModel
like you normally would using WPF and the MVVM pattern.Next you need to bind a
View
to your newViewModel
.Then you create an instance of the
ViewModel
and add it to the collection in yourMainWindowViewModel
.And now the
TabItem
should show up in yourTabControl
.Loading TabItems dynamically using Extensions:
In some cases you might even need to load
TabItems
from plugins dynamically without the host application first knowing about theTabItem
. In these cases you need to have the plugin register theView
andViewModel
with the application domain.This is very easy to do, and actually something I do for one of my
MEF
based projects. I have an post here, with some additional details as well.All you need to do is add a
Resource Dictionary
to your plugin/extension and make sure that the host application loads it once the plugin has been imported.To show you a fast example I would have a
View.xaml
in my extensions:I then expose the ResourceDictinary using MEF to the Host like this:
Last you use
Application.Current.Resources.MergedDictionaries.Add
to load the View.xaml into the host.you dont have to add controls if you use mvvm. you just have to create datatemplates for your viewmodel objects you wanna display.
all you need is a contentcontrol/presenter which is bind to your viewmodel and the datatemplate will show what you want.