0
votes

I have a MainWindowView(Window) with a Canvas in which I add my Views(UserControls).

The Canvas in the MainWindow is a Custom Canvas derived from Canvas so that Views inside this can be moved here and there, and can bringtofront or sendback.

I add Views to MainWindowView's Canvas by Binding a Command to a Button. So when I click a Button, a View gets added in the Canvas.

But, my problem is, I want to add another View to the same Canvas of MainViewModel from the ViewModel of my Views which are already in the Canvas of MainViewModel.

Since the ObservableCollection, which I used to bind Canvas, is in MainViewModel, I can add View from the MainViewModel only.

When I try to use the MainViewModel from other ViewModel, I have to create a new object of it, which makes the old View in the Canvas being replaced by the new one.

Is there a solution for this. If not what's the use of using MVVM framework. Please help...

2
Are you using a framework? Can't you just add the child controls between the <Canvas> tags? Or are you asking about binding?tzerb
There are many ChildControl and user decide them by clicking on a button, so i have to dynamically addKishore Kumar
Can you add some description? I can't figure out which is the problemRoberto
I have updated the question to have much better description. If you need some more, let me know.Kishore Kumar
you have a problem similar to mine where you have a MianViewModel and ViewModel for each child added stackoverflow.com/q/10404313/816721 You can see my solution but has a drawback is not completely MVVMrkmax

2 Answers

1
votes

Use Calibrum Micro, which will help you in this

1
votes

Am I getting this right : Your controls' DataContext is a Different one than that of the Window and you need to access it from there?

Basically that could have been avoided by design (use Dependency Injection to get the MainViewModel instance into the Command), but in fact there is a WPF/MVVM friendly way of solving this:

Use Commands to Add Controls to the MainViewModels ObservableCollection

<Button Command="{Binding Path=CreateViewCommand}" CommandParameter="{Binding}" />

From your Control (what you called View), you must use Ancestor Binding:

<Button Command="{Binding Path=DataContext.CreateViewCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"
    CommandParameter="{Binding Path=DataContext, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"/>

In your Command, you can cast the parameter to its original Type (MainViewModel) and work with it as you wish.