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

WPF中如何在XAML里组合多个字符串静态资源?

在XAML中组合多个字符串静态资源的方法

要在XAML中组合UntitledFileName和ApplicationName两个静态字符串资源生成DefaultWindowTitle,可以用以下两种常用方案:

方案一:使用MultiBinding + StringFormat

这种方法直接通过多绑定拼接字符串,是最常用的实现方式:

<sys:String x:Key="UntitledFileName">Untitled</sys:String>
<sys:String x:Key="ApplicationName">SomeAppName</sys:String>

<!-- 定义组合后的标题资源 -->
<MultiBinding x:Key="DefaultWindowTitle" StringFormat="{}{0} - {1}">
    <Binding Source="{StaticResource UntitledFileName}" />
    <Binding Source="{StaticResource ApplicationName}" />
</MultiBinding>

使用时直接绑定该资源即可:

<Window Title="{StaticResource DefaultWindowTitle}" ...>

方案二:使用ObjectDataProvider调用String.Format

这种方式利用String.Format方法实现字符串拼接:

<sys:String x:Key="UntitledFileName">Untitled</sys:String>
<sys:String x:Key="ApplicationName">SomeAppName</sys:String>

<ObjectDataProvider x:Key="DefaultWindowTitle" MethodName="Format" ObjectType="{x:Type sys:String}">
    <ObjectDataProvider.MethodParameters>
        <sys:String>{0} - {1}</sys:String>
        <StaticResource ResourceKey="UntitledFileName" />
        <StaticResource ResourceKey="ApplicationName" />
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

使用方式:

<Window Title="{Binding Source={StaticResource DefaultWindowTitle}}" ...>

注意事项

无法直接将DefaultWindowTitle定义为sys:String类型的静态资源,因为静态字符串资源的值是编译时固定的,而字符串拼接需要动态解析资源引用。上述两种方案都是通过绑定机制实现动态组合,能满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:15:35