我可能错过了点,在这里,我一直在四处寻找了一段时间,看着the different approaches绑定的意见和视图模型,以及如何在它们之间进行导航。WPF从ICommand的回的MainView
设置:
- 1主窗口(视图模型:
MainWindowViewModel
) - 主窗口包含一些视觉效果和被绑定到一个
ViewModelBase
一个ContentControl
。所以在MainWindowViewModel
我可以设置任何其他视图(模型)来显示。 - 得到两个用户控件,一个是一个登录表单,另外一个是用于现在的负载指示器。
里面的App.xaml
<DataTemplate DataType="{x:Type vms:LoginViewModel}">
<Views:LoginView />
</DataTemplate>
<DataTemplate DataType="{x:Type vms:LoadingViewModel}">
<Views:LoadingView />
</DataTemplate>
目标: 从ICommand的内部LoginViewModel
回到MainWindowViewModel
,长着表单数据。然后MainWindowViewModel
将切换到LoadingViewModel
,做异步调用的服务。下次在保存刷新令牌时,我将显示LoadingViewModel
而不是登录表单。完成后将打开一个新窗口(或其他东西,目前还不知道)。
问题:大多数例子说明如何做到这一点,当一个按钮既是用户控件之外,所以当ICommand的是主窗口内,那么这将是容易的,但该事件从子视图的一个叫。使用PropertyChange似乎也有点偏离。
让我们深入到一些代码,外壳我们?
MainWindow.xaml中,只有一个重要的一行
<ContentControl Content="{Binding CurrentView}" Grid.Column="1" Grid.Row="1" />
MainWindow.xaml.cs,在构造
this.DataContext = new MainWindowViewModel();
MainWindowViewModel
public class MainWindowViewModel
{
public ViewModelBase CurrentView { get; set; }
public MainWindowViewModel()
{
CurrentView = new LoginViewModel();
}
}
LoginViewModel
public class LoginViewModel : ViewModelBase
{
public DelegateCommand loginCommand { get; set; }
public LoginViewModel()
{
loginCommand = new DelegateCommand(Execute, CanExecute);
}
private bool CanExecute()
{
return true;
}
private void Execute()
{
//I need to go to MainWindowViewModel
throw new NotImplementedException();
}
//more properties below heere.
0从级
ViewModelBase
继承(从棱镜),这样处理的PropertyChanged事件。我的视图模型中的属性使用正确的SetProperty
方法。 我不喜欢使用Prism的区域,IEventAggregator或Unitiy。
解决方案
想到什么长正在发送接口与构造,并使用界面做“回调”到MainWindowViewModel
,但我想这会给错误,因为我将更改视图,从而设置MainWindowViewModel.CurrentView
别的东西,留下LoginViewModel
空。由于请求来自该对象,我可以想象它并不是很好。
如何有关处理这一切在你的'ViewModelBase'的getter和setter。这是唯一的地方,你将在你的处理器同时拥有新旧价值。 – XAMlMAX
你做错了。没有ViewModel应该知道什么关于Views。整个想法是,你的Views和ViewModel应该完全分开,你应该能够完全改变你的View或ViewModel,它仍然应该工作。 –
@NawedNabiZada是的,我知道。这就是为什么我将3个视图模型分开的原因。我没有看到我在MVVM中做了什么,直到现在它只是基本的实现。有时候,有些要求使MVVM少一点,也许这就是其中之一,但我正在寻找一种最适合MVVM的解决方案,当然还有坚实的代码。 XAMIMAX:呃,这是两个不同的例子,我并不需要新旧价值。 – CularBytes