2010-01-12 163 views
1

這是我的「示例代碼」,包括我正在嘗試做的事情。顯然,目前它不工作,但有什麼辦法可以使它工作?如何從WPF中的其他字符串資源構建字符串資源?

<ResourceDictionary 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" 
    > 
    <System:String x:Key="ProductName">Foo</System:String> 
    <System:String x:Key="WindowTitle">{ProductName} + Main Window</System:String> 
</ResourceDictionary> 
+0

您可以使用xaml中的字符串格式來實現相同的目標嗎?http://blogs.msdn.com/llobo/archive/2008/05/19/wpf-3-5-sp1-feature-stringformat.aspx – 2010-01-12 22:42:01

回答

2

到計算字符串以這種方式添加到ResourceDictionary中的唯一方法是創建一個MarkupExtension。你MarkupExtension將用於這樣的:

<ResourceDictionary ...> 
    <sys:String x:Key="ProductName">Foo</sys:String> 
    <local:MyStringFormatter 
    x:Key="WindowTitle" 
    StringFormat="{0} Main Window" 
    Arg1="{StaticResource ProductName}" /> 
</ResourceDictionary> 

這裏假設你已經創建了你的「本地」命名空間的MarkupExtension子命名MyStringFormatterExtension有一個名爲「的StringFormat」性質,「ARG1」,「Arg2所得」等,並有一個明顯的ProvideValue()方法。

請注意,正如Aran指出的,使用StringFormatterBinding是獲得相同效果的更常見方法,並且通常是更好的設計。權衡是不允許將結果用作ResourceDictionary的一部分。

+0

優秀 - 我在搜索中沒有遇到過這些概念。謝謝! – Ant 2010-01-13 09:07:53