Click here to Skip to main content
15,917,859 members
Please Sign up or sign in to vote.
2.67/5 (3 votes)
In order to enable drag-drop properly between two user controls, I need to call their viewmodels from the MainWindow viewmodel

I had thought that it would be as simple as this:

XML
<UserControl x:Class="LookupTermWizard.View.Properties"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:b="clr-namespace:LookupTermWizard.Behavior"
        xmlns:vm="clr-namespace:LookupTermWizard.ViewModel"
        Height="300" Width="500" removed="LightGray" DataContext="{Binding}" >


XML
<Window x:Class="LookupTermWizard.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:LookupTermWizard.ViewModel"
        xmlns:v="clr-namespace:LookupTermWizard.View"
        xmlns:b="clr-namespace:LookupTermWizard.Behavior"
        Title="Lookup Term Wizard" Height="900" Width="1300">
    <Window.DataContext>
        <vm:MainWindowViewModel />
    </Window.DataContext>
        <StackPanel DockPanel.Dock="Left" VerticalAlignment="Top" Height="775" >
            <ContentControl>
                <v:Properties DataContext="{Binding PropertiesVM}" />
            </ContentControl>


And then instantiate the viewmodel for the user control from the MainWindowViewModel

C#
PropertiesViewModel propertiesVM;

PropertiesViewModel PropertiesVM
{
    get { return propertiesVM; }
    set
    {
        propertiesVM = value;
        OnPropertyChanged("PropertiesVM");
    }
}
public MainWindowViewModel()
{
    PropertiesVM = new PropertiesViewModel();

}


Of course, it doesn't work that way. Any chance of getting some guidance?
Posted
Comments
Matt T Heffron 21-Sep-12 18:23pm    
So what is going wrong? Binding failing?
(I noticed that PropertiesVM is not shown here as public...)
You shouldn't use the DataContext={Binding} in the Properties XAML. The DataContext has been explicitly set in the MainWindow.
(Also, since v:Properties is a UserControl, why wrap it in ContentControl?)
Bob Brady 24-Sep-12 8:53am    
Oh, my God, I'm stupid. Yes, the problem was that I left public off of the PropertiesViewModel. I can't believe that. That's what I get for working late on a Friday, huh?

Thanks, Matt.

As for the UserControl - that's the only way I know of to invoke it. I've been a WPF/MVVM programmer for about 3 weeks. Normally I do websites.
Member 11248861 13-Aug-15 1:53am    
Thanx alot I got this doing for me same problem.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900