[英]WPF MVVM switch usercontrols
I am new to MVVM and WPF but I know what's going on in MVVM. 我是MVVM和WPF的新手,但我知道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.
在我的应用程序中,我有:MainWindow.xaml,带有日志和2个链接:显示全部并创建新的。 Of course I have ViewModel for it.
当然我有ViewModel。 I have 2 more UserControls: ShowAll and Create with ViewModels and all logic in it (adding data etc).
我还有2个UserControls:ShowAll和Create with ViewModels以及其中的所有逻辑(添加数据等)。 How can I show create form when I click link Create new or show all when I click ShowAll?
当我单击链接时创建新建或单击ShowAll时显示全部,如何显示创建表单?
In windowForms I just hide UC, buto here is no code behind :) 在windowForms我只是隐藏UC,但是这里没有代码:)
My MainWindow.xaml: 我的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>
My MainWindowViewModel: 我的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;
}
}
In Create and ShowAll there is no code. 在Create和ShowAll中没有代码。 In xaml only a label, VM is empty.
在xaml中只有一个标签,VM是空的。 Just for test.
只是为了测试。
Thank's for help! 感谢帮助!
You can use a ContentControl
to display a specific DataTemplate
based on the type of ViewModel that is bound to the ContentControl
. 您可以使用
ContentControl
根据绑定到ContentControl
的ViewModel的类型显示特定的DataTemplate
。
http://www.japf.fr/2009/03/thinking-with-mvvm-data-templates-contentcontrol/ http://www.japf.fr/2009/03/thinking-with-mvvm-data-templates-contentcontrol/
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. 绑定到ShowAll按钮的命令可以简单地更改主ViewModel上的属性,该属性绑定到内容控件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.