gpt4 book ai didi

c# - 在 WPF MVVM 中添加新的用户控件按钮单击命令

转载 作者:行者123 更新时间:2023-11-30 20:41:57 26 4
gpt4 key购买 nike

您好,我正在尝试动态显示用户控件,但它不起作用...请帮助我改进代码。在 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");
}
}

关于c# - 在 WPF MVVM 中添加新的用户控件按钮单击命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31832289/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com