Loading user controls dynamically in Mainwindow when value in dropdown changes

时间:2016-07-28 20:24:59

标签: c# wpf mvvm

I'm working on a C# WPF application.I've a list of user controls UC1,UC2 and UC3 having a ViewModel for each.And all internally refer to another common user control called UCB. And my App.xaml refers to MainWindow.xml

UCB has a dropdown list with names of different account types.

I need to programmatically show the user control in MainWindow depending upon the account type selected in the Base user control UCB.How do I achieve this please?

My thoughts so far: May be I can instantiate all my user controls in MainWindow.xaml.cs file like this:

    UserControl uc1 = (UserControl)assembly.CreateInstance(string.Format("{0}.MyUC1", type.Namespace));
    UserControl uc2 = (UserControl)assembly.CreateInstance(string.Format("{0}.MyUC2", type.Namespace));   

userControls.Add("1", uc1);
userControls.Add("2", uc2);

and then use the MainWindow.xaml's content property to set the desired user control based on the dropdown value.

this.Content = userControls["1"];

But how do I access this content property inside ComboBox_SelectionChanged event in UCB control??

Please advise.

Thanks.

1 个答案:

答案 0 :(得分:2)

您可以添加Dropdown / ContentControl,根据ContentPresenter选择切换视图,希望您的UserControls具有不同的ViewModel

例如:

<ContentPresenter Content="{Binding CurrentViewModel}">
   <ContentPresenter.Resources>
            <DataTemplate DataType="{x:Type ViewModel:UC1VM}">
                <Views:UC1/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type ViewModel:UC2VM}">
                <Views:UC2/>
            </DataTemplate>
        </ContentPresenter.Resources>
</ContentPresenter>    

UCB ViewModel中,您应该拥有如下所示的Objact属性

 private object _CurrentViewModel;
 public object CurrentViewModel
 {
        get { return _CurrentViewModel; }
        set { _CurrentViewModel = value; NotifyPropertyChanged(); }
 }

现在,当您从DropDown中选择一个项目时,会为ViewModel创建相应的View。并将CurrentViewModel分配给您新创建的ViewModel。这将显示您想要的View