菜单栏点击切换的实现
WPF Multiple Views in One Window
实现的内容
单击不同的按钮在同一个窗口中显示不同的界面
参考:https://www.youtube.com/watch?v=xUwk2-_tRzo
1.新建WPF工程项目,命名为Multiple Views. 在解决方案中新建两个文件夹ViewModels与Views来存放各种视图,具体的内容后面说。
2.设计主界面(MainWindow.xaml):
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<DockPanel Grid.Column="0" Grid.Row="0" Grid.RowSpan="5" Background="Gray">
<StackPanel>
<Button Content="red view" Click="RedView_Click"/>
<Button Content="Blue view" Click="BlueView_Click"/>
</StackPanel>
</DockPanel>
<ContentControl Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="4" Grid.RowSpan="5" Content="{Binding}"/>
</Grid>
说明:分成了5行5列,第1列作为菜单项,放了两个按钮,第2-5列放ContentControl。
目前,我们想的是点击左边不同的按钮,会在ContentControl中显示不同的界面。
3.设计需要在ContentControl中显示的界面
在Views文件夹中添加->新建项->用户控件(User Control),重命名为RedView.xaml
其中的代码为:
<UserControl x:Class="Multiple_Views.Views.RedView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Multiple_Views.Views"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid Background="Red">
</Grid>
</UserControl>
这里仅仅设置了背景,可以自行添加其他的控件功能。
同样的,添加BlueView.xaml 将Background设置为Blue。
4.在ViewModels文件夹中,添加->新建项->类, 重命名为BlueViewModel.cs.里面会自动生成一个BlueViewModel类。
namespace Multiple_Views.ViewModels
{
class BlueViewModel
{
}
}
同样的添加RedViewModel.cs
5.想要实现功能,还需再编辑MainWindow.xaml代码
由于在不同的文件夹,添加命名空间:
<
xmlns:viewmodels="clr-namespace:Multiple_Views.ViewModels"
xmlns:views="clr-namespace:Multiple_Views.Views"
>
添加Window.Resources并使用DataTemplate
<Window.Resources>
<DataTemplate x:Name="blueViewTemplate" DataType="{x:Type viewmodels:BlueViewModel}">
<views:BlueView DataContext="{Binding}"/>
</DataTemplate>
<DataTemplate x:Name="redViewTemplate" DataType="{x:Type viewmodels:RedViewModel}">
<views:RedView DataContext="{Binding}"/>
</DataTemplate>
</Window.Resources>
6.最后,为两个button添加Click事件,
private void RedView_Click(object sender, RoutedEventArgs e)
{
DataContext = new RedViewModel();
}
private void BlueView_Click(object sender, RoutedEventArgs e)
{
DataContext = new BlueViewModel();
}
访问链接:https://blog.csdn.net/Xuxianmincs/article/details/81842912?utm_medium=distribute.pc_relevant_download.none-task-blog-baidujs-1.nonecase&depth_1-utm_source=distribute.pc_relevant_download.none-task-blog-baidujs-1.nonecase
浙公网安备 33010602011771号