WPF MVVM切换用户控件 [英] WPF MVVM switch usercontrols
问题描述
我是新来MVVM和WPF,但我知道这是怎么回事在MVVM。我有在主窗口的用户控件之间切换的问题。在我的应用程序,我有:日志和2个链接
MainWindow.xaml:显示所有和新建。当然,我的ViewModel它。我有2个以上用户控件:和勾住ShowAll用的ViewModels和它所有的逻辑(添加数据等)的创建。我该怎么让创建表单,当我点击链接新建或显示所有当我点击勾住ShowAll?
I am new to MVVM and WPF but I know what's going on in MVVM. I have a problem with switching between user controls in mainwindow. In my app I have: MainWindow.xaml with log and 2 links: Show all and Create new. Of course I have ViewModel for it. I have 2 more UserControls: ShowAll and Create with ViewModels and all logic in it (adding data etc). How can I show create form when I click link Create new or show all when I click ShowAll?
在windowForms我只是躲在UC,这里布托没有后面的代码:)
In windowForms I just hide UC, buto here is no code behind :)
我的MainWindow.xaml:
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:
My 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;
}
}
在创建和SHOWALL没有任何代码。 XAML中的一个标签,VM是空的。只是为了测试。
In Create and ShowAll there is no code. In xaml only a label, VM is empty. Just for test.
感谢的帮忙!
推荐答案
可以使用 ContentControl中
来显示特定的DataTemplate
基于绑定到 ContentControl中
。
You can use a ContentControl
to display a specific DataTemplate
based on the type of ViewModel that is bound to the ContentControl
.
的 http://www.japf.fr/2009/03/thinking-with-mvvm-data-templates-contentcontrol/
这是绑定到按键勾住ShowAll命令可以简单地改变你的主视图模型的属性是什么绑定到您的内容控制。
The command that is bound to the ShowAll button can simply change a property on your main ViewModel which is what is bound to your content control.
这篇关于WPF MVVM切换用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!