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

如何在UWP桌面应用中将文本文件作为XAML应用资源添加?

如何在WPF的Application.Resources中定义文本资源

当然可以在WPF的Application.Resources中定义文本文件相关的资源,根据文本内容的长度和存储方式,有两种常用实现方式:

方式一:直接嵌入短文本内容

适合内容较短的文本,直接在XAML中定义String类型的资源:

步骤1:引入System命名空间

在Application根标签中添加System命名空间引用:

<Application x:Class="YourAppName.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:system="clr-namespace:System;assembly=mscorlib"
             StartupUri="MainWindow.xaml">

步骤2:定义文本资源

在<Application.Resources>节点中添加文本资源:

<Application.Resources>
    <!-- 已有的图像资源 -->
    <Image x:Key="Img_DefaultCover" Source="/Images/defaultCover.png" />
    <!-- 新增的短文本资源 -->
    <system:String x:Key="Txt_WelcomeMsg">欢迎使用本应用!</system:String>
    <system:String x:Key="Txt_ErrorTip">操作失败,请重试</system:String>
</Application.Resources>

使用资源

  • 在XAML中直接引用:
<TextBlock Text="{StaticResource Txt_WelcomeMsg}" />
  • 在C#代码中读取:
string welcomeText = Application.Current.Resources["Txt_WelcomeMsg"] as string;

方式二:引用外部文本文件(长文本)

如果文本内容较长(比如帮助文档、协议文本),可以将外部.txt文件嵌入为资源,再在XAML中定义读取逻辑:

步骤1:配置文本文件属性

将目标文本文件(比如/Assets/HelpDoc.txt)的生成操作设置为Resource(右键文件→属性→生成操作),这样文件会被嵌入到程序集中。

步骤2:在XAML中定义资源

使用ObjectDataProvider读取外部文本文件内容并作为资源:

<Application.Resources>
    <!-- 已有的图像资源 -->
    <Image x:Key="Img_DefaultCover" Source="/Images/defaultCover.png" />
    <!-- 引用外部文本文件的资源 -->
    <ObjectDataProvider x:Key="Txt_HelpDoc"
                        ObjectType="{x:Type system:IO.File}"
                        MethodName="ReadAllText">
        <ObjectDataProvider.MethodParameters>
            <!-- 路径格式:pack://application:,,,/程序集名;component/文件路径,当前程序集可简化为/文件路径 -->
            <system:String>/Assets/HelpDoc.txt</system:String>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Application.Resources>

使用资源

  • 在XAML中绑定使用:
<TextBlock Text="{Binding Source={StaticResource Txt_HelpDoc}}" 
           TextWrapping="Wrap" />
  • 在C#代码中读取:
var helpDocProvider = Application.Current.Resources["Txt_HelpDoc"] as ObjectDataProvider;
string helpDocContent = helpDocProvider?.ObjectInstance as string;

内容的提问来源于stack exchange,提问作者Jose Afonso Braga

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:09:24