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
相关产品推荐
相关产品推荐

