我是MVVM和WPF的新手,但我知道MVVM中发生了什么。我在主窗口中切换用户控件时遇到问题。在我的应用程序中,我有: 带有日志和2个链接的MainWindow.xaml:显示全部并创建新的。当然我有ViewModel。我还有2个UserControls:ShowAll和Create with ViewModels以及其中的所有逻辑(添加数据等)。当我单击链接时创建新建或单击ShowAll时显示所有内容,如何显示创建表单?
在windowForms中,我只是隐藏了UC,但是这里没有代码背后的代码:)
My MainWindow.xaml:
<Window x:Class="Test.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="300">
<Grid>
<StackPanel>
<TextBox Text="{Binding Name}"/>
<Button Content="Change" Command="{Binding ChangeCommand}"/>
</StackPanel>
</Grid>
</Window>
我的MainWindowViewModel:
class MainWindowViewModel : BaseViewModel
{
private Person _person;
private BaseCommand _changeCommand;
public MainWindowViewModel()
{
_person = new Person();
}
public string Name
{
get
{
return _person.Name;
}
set
{
if (_person.Name != value)
_person.Name = value;
OnPropertyChanged(() => Name);
}
}
public ICommand ChangeCommand
{
get
{
if (_changeCommand == null)
_changeCommand = new BaseCommand(() => change());
return _changeCommand;
}
}
private void change()
{
_person = new Person();
Name = _person.Imie;
}
}
在Create和ShowAll中没有代码。在xaml中只有一个标签,VM是空的。仅供测试。
感谢您的帮助!
答案 0 :(得分:8)
您可以使用ContentControl
根据绑定到DataTemplate
的ViewModel类型显示特定的ContentControl
。
http://www.japf.fr/2009/03/thinking-with-mvvm-data-templates-contentcontrol/
绑定到ShowAll按钮的命令可以简单地更改主ViewModel上的属性,该属性绑定到内容控件。