You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Visual Studio中XAML文件的默认代码布局?

修改VS2022中WPF XAML模板(UserControl/Page/Window)的方法

和你修改C#类模板的思路一致,WPF的XAML项模板同样存放在VS安装目录的对应文件夹中,具体操作如下:

  1. 定位模板文件路径
    VS2022企业版的WPF项模板根目录为:
    C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\ItemTemplates\CSharp\WPF\1033
    该目录下的子文件夹对应不同的XAML项类型:

    • UserControl模板:UserControl\UserControl.xaml
    • Window模板:Window\Window.xaml
    • Page模板:Page\Page.xaml
  2. 修改模板内容
    找到对应模板文件后(需管理员权限打开编辑),直接修改XAML代码为你需要的默认格式。比如针对UserControl,你可以预设Width、Height和DataContext:

    <UserControl x:Class="$rootnamespace$.$safeitemname$"
                 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:$rootnamespace$"
                 mc:Ignorable="d"
                 Width="800" Height="450"
                 DataContext="{Binding RelativeSource={RelativeSource Self}}">
        <Grid>
            
        </Grid>
    </UserControl>
    

    注意保留$rootnamespace$、$safeitemname$这类VS内置的模板变量,它们会在创建文件时自动替换为项目命名空间和文件名。

  3. 生效设置(可选)
    如果修改后创建新项时未生效,需清理VS模板缓存:

    • 以管理员身份打开命令提示符
    • 运行命令:devenv /installvstemplates
    • 重启Visual Studio即可

内容的提问来源于stack exchange,提问作者Snail

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 12:12:20