【6月日新计划13】WPF入门-Window, UserControl和Page的区别

593 阅读1分钟

【6月日新计划13】WPF入门-Window,UserControl和Page的区别

1. Scenario

當我們在WPF項目中,右鍵添加新建項時,通常會有很多選項,常用的這三個Window、UserControl 和 Page 都是用于创建用户界面的基本元素。

图片.png

2. Window

Window 是 WPF 中最常用的容器控件,它表示一个独立的窗口。Window 可以包含其他控件,如 Button、TextBox 和 DataGrid等。通常情况下,Window 用于创建应用程序的主窗口或子窗口。

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <!-- 这里可以添加其他控件 -->
    </Grid>
</Window>

3. UserControl

UserControl 是一个可重用的控件,它可以作为子控件嵌入到 Window 或其他 UserControl 中。

<UserControl x:Class="WpfApp1.MyUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Height="300" Width="300">
    <Grid>
        <!-- 这里可以添加其他控件 -->
    </Grid>
</UserControl>

4. Page

Page 表示应用程序中的一个页面。通常情况下,Page 用于创建导航应用程序,其中用户可以通过导航到不同的页面来访问应用程序中的不同功能。

<Page x:Class="WpfApp1.MyPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="My Page">
    <Grid>
        <!-- 这里可以添加其他控件 -->
    </Grid>
</Page>