MVVM datatemplate binding multiple views

Oct 21, 2010 at 12:57 AM

Hi,

I am trying to create a dynamic tabbing functionality, when a user clicks a button it will create a tab with its own view and its own viewmodel.

I am using a DataTemplate to achieve this:

<DataTemplate x:Shared="False" DataType="{x:Type vm:CustomCanvasViewModel}">
            <wpfview:CustomCanvas>
            </wpfview:CustomCanvas>
        </DataTemplate>


I also have a :

  public ObservableCollection<CustomCanvasViewModel> Workspaces { get; set; }

Workspaces.Add( new CustomCanvasViewModel ());

So I am binding the tabcontrol with Workspaces. The problem i am having is that all the view's are being shared though all the created tabs. So any changes made to a tab it is reflecting across all of them.

I am not sure if a missing something or how would you recommend to achieve this.

I will really appreciate your help.


Thanks in Advance.


Jose

Oct 23, 2010 at 2:51 PM

Are you using dependency injection for your viewmodels?  If yes is it passing in the same viewmodel for each instance? you may need to change your dependency injection to use transient.

Oct 25, 2010 at 5:17 PM

Nop, I am not using dependency injection.

I am just binding the view model and view by using a data template of the viewmodel type.

Should I use it? If so how would you recommend to do it?

Thanks In Advance.
Jose

Coordinator
Nov 29, 2010 at 2:26 PM

Hi,

With or without dependency injection, what you need in the case where the same view is instantiated multiple times is to instantiate the corresponding viewmodel multiple times too. Instead of using a singleton viewmodel, return a different viewmodel when the property is called.

Makes sense?

Cheers,

Laurent

Dec 22, 2010 at 10:07 PM

 

I'm probably a little late in replying but I momentarily had this issue to when I realized that within the view model I was reusing some common data components. So its possible that the view itself looks like its the same because the underlying data in the view model is the same. You may want to check that out.  Also, you can setup messaging to send messages to your workspace view model to open new "editors" or even close the current one. This helps decouple the workspaces view model from the rest of the application.