我想在WPF应用程序中实现导航。目前StartScreen.xaml在启动时显示,但是当我单击按钮时,未显示DeviceManagement.xaml。甚至不会调用 ShowDeviceManagement 命令。
这让我假设 Button 的 Command 不正确?我该如何解决?
的App.xaml
<Application.Resources>
<DataTemplate DataType="{x:Type vm:DeviceManagementViewModel}">
<view:DeviceManagement />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:MainWindowViewModel}">
<view:StartScreen />
</DataTemplate>
</Application.Resources>
MainWindow.xaml
<Window ...>
<Window.DataContext>
<vm:MainWindowViewModel/>
</Window.DataContext>
<ContentControl
Content="{Binding ViewModel}">
</ContentControl>
</Window>
StartScreen.xaml
<UserControl ...>
<Button
Content="Click Me"
Command="{Binding DataContext.ShowDeviceManagement, RelativeSource={RelativeSource AncestorType={x:Type vm:MainWindowViewModel}}, Mode=OneWay}"/>
</UserControl>
MainWindoViewModel.cs
class MainWindowViewModel : ViewModelBase
{
public ViewModelBase ViewModel { get; set; }
public MainWindowViewModel()
{
ViewModel = this;
}
public ICommand ShowDeviceManagement
{
get
{
return new RelayCommand(action => ViewModel = new DeviceManagementViewModel());
}
}
}
答案 0 :(得分:1)
“DataContext”在命令绑定中已过时。 RelativeSource用于在可视树中查找祖先,而您的MainWindowViewModel不是Visual。应该是这样的:
Command="{Binding ShowDeviceManagement, Mode=OneWay}"