如何在UWP中创建带有代码后置(*.cs)文件的新页面
创建带代码后置文件的XAML页面方法
方法一:通过Visual Studio正确创建
- 右键项目 → 选择「添加」→「新建项」
- 在弹出的模板窗口里,选**「XAML页面」**(别选「XAML视图」),输入页面名称后确认,IDE会自动生成配对的
.xaml和.xaml.cs代码后置文件。
方法二:手动为现有XAML View补全代码后置
如果已经创建了无代码后置的XAML View,按以下步骤补全:
- 在同一目录下新建一个同名的
.cs文件,比如MyPage.xaml.cs - 编辑这个
.cs文件,编写partial类,继承对应基类(如Page),并添加构造函数调用InitializeComponent():
using Windows.UI.Xaml.Controls; namespace 你的项目命名空间 { public partial class MyPage : Page { public MyPage() { InitializeComponent(); } } }
- 修改
MyPage.xaml的根元素,添加x:Class属性,指定对应的命名空间和类名:
<Page x:Class="你的项目命名空间.MyPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <!-- 这里写页面内容 --> </Page>
- 检查项目文件(
.csproj),确保两个文件关联正确,添加或修改以下配置:
<ItemGroup> <Page Include="MyPage.xaml"> <DependentUpon>MyPage.xaml.cs</DependentUpon> </Page> <Compile Include="MyPage.xaml.cs"> <DependentUpon>MyPage.xaml</DependentUpon> </Compile> </ItemGroup>
内容的提问来源于stack exchange,提问作者ricky rocky
相关产品推荐
相关产品推荐

