简体   繁体   English

在“添加新的用户控件”按钮上单击“在WPF MVVM中单击命令”

[英]Add New Usercontrol On button Click Command In WPF MVVM

Hi i am trying to display usercontrol Dynamically But it is not working ...please help me to improve code . 嗨,我正在尝试动态显示usercontrol,但是它不起作用...请帮助我改善代码。 In cunstructor of MainWindowViewModel i tried to set initial property of contentcontrol. 在MainWindowViewModel的cunstructor中,我尝试设置contentcontrol的初始属性。 Thank you in advance 先感谢您

<Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:VM="clr-namespace:WpfApplication1.ViewModel"
            xmlns:View="clr-namespace:WpfApplication1.View"
            Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <DataTemplate DataType="{x:Type VM:FirstControlViewModel}">
                <View:FirstControl></View:FirstControl>
            </DataTemplate>
            <DataTemplate DataType="{x:Type VM:SecondControlViewModel}">
                <View:SecondControl></View:SecondControl>
            </DataTemplate>

        </Window.Resources>
        <Grid>
            <ContentControl Content="{Binding LoadedControl}" />
        </Grid>
    </Window>

View Model Code :- 查看型号代码:-

    public class MainViewModel: INotifyPropertyChanged        
    {
       public MainViewModel()
       {
           LoadedControl = "FirstControlViewModel";// here i am setting property  
                                                   //But not working
       }

       private string _LoadedControl;

       public string LoadedControl
       {
           get { return _LoadedControl; }
           set { _LoadedControl = value;

           NotifyPropertyChanged("LoadedControl");

           }
       }

You need to set LoadedControl to an instance of your ViewModel type, not a string! 您需要将LoadedControl设置为ViewModel类型的实例,而不是字符串!

public MainViewModel()
{
   LoadedControl = new FirstControlViewModel();
}

private ViewModelBase _LoadedControl;

public ViewModelBase LoadedControl
{
    get { return _LoadedControl; }
    set { _LoadedControl = value;
          NotifyPropertyChanged("LoadedControl");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM