4
我试图按照答案provided in this post,但我必须错过一些微不足道的东西。我定义我的DataTemplate
S作为App.xaml
如下:使用MVVM的WPF导航
<Application.Resources>
<DataTemplate DataType="{x:Type vm:BlowerViewModel}">
<v:BlowerView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:HomeViewModel}">
<v:HomeView />
</DataTemplate>
</Application.Resources>
然后,在我的MainWindow.xaml
我已经定义了下面的代码:
<Window x:Class="App.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:App.UI.ViewModel"
Title="MainWindow" SizeToContent="WidthAndHeight">
<Window.DataContext>
<vm:MainViewModel />
</Window.DataContext>
<ContentControl Content="{Binding CurrentView}" />
</Window>
为MainViewModel
的代码包含一个属性CurrentView
和ICommand
所以我可以切换视图。定义如下:
public class MainViewModel : BaseViewModel
{
private BaseViewModel _currentView;
public MainViewModel()
{
CurrentView = new HomeViewModel();
}
public BaseViewModel CurrentView
{
get { return _currentView; }
set
{
if (_currentView != value)
{
_currentView = value;
RaiseChangedEvent("CurrentView");
}
}
}
public ICommand SwitchView {
get {
return new CommandHandler(() => SwitchBlower());
}
}
protected void SwitchBlower()
{
CurrentView = new BlowerViewModel();
}
}
在我HomeView.xaml
,我已经定义了一个按钮链接到MainViewModel
执行SwitchView ICommand
。如下所示。
<UserControl x:Class="App.UI.View.HomeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:App.UI.ViewModel"
Height="300" Width="300">
<Grid>
<TextBlock>This is the homeview</TextBlock>
<Button Command="{Binding DataContext.SwitchView, RelativeSource={RelativeSource AncestorType={x:Type vm:MainViewModel}}, Mode=OneWay}" Content="Test" />
</Grid>
</UserControl>
当我启动应用程序时,它没有注册事件,点击按钮不会触发事件来改变视图。我已经尝试在ICommand get
和函数调用本身中加入断点。起初,我想也许我需要来定义我的数据模板MainViewModel
,但这样做在下面的错误结果(即使该项目构建罚款)
不能把窗口的风格
任何人都可以提供我需要得到这个工作缺少的一块?
AncestorType应该是MainWindow而不是MainViewModel。 MainViewModel不是可视树的一部分。匆匆一瞥,其他一切看起来都很好。 –
@LeeO。如果您想将其作为答案发布,我会很乐意将其标记为已接受。看起来这是我的隧道视野案例!谢谢一堆。 – entropic
看起来你现在全部排序,做得很好。 – Sheridan