簡體   English   中英

在“添加新的用戶控件”按鈕上單擊“在WPF MVVM中單擊命令”

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

嗨,我正在嘗試動態顯示usercontrol,但是它不起作用...請幫助我改善代碼。 在MainWindowViewModel的cunstructor中,我嘗試設置contentcontrol的初始屬性。 先感謝您

<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>

查看型號代碼:-

    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");

           }
       }

您需要將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