我使用WPFLocalizationExtension(可在CodePlex)本地化我的WPF應用程序中的字符串。這個簡單的MarkupExtension行之有效的簡單的場景是這樣的:MarkupExtension:將簡單的屬性轉換爲DependencyProperty
<Button Content="{lex:LocText MyApp:Resources:buttonTitle}" />
但我嘗試了一些更復雜的東西就像我得到了,一旦卡:
<Window Title="{lex:LocText MyApp:Resources:windowTitle, FormatSegment1={Binding Version}}" />
(帶有資源windowTitle = "MyApp v{0}"
)。
由於FormatSegment1是一個普通的INotifyPropertyChange屬性,我無法將任何東西綁定到它。如果FormatSegment1是DependencyProperty,那麼我可能會下載源代碼並試圖修補。
我修改
[MarkupExtensionReturnType(typeof(string))]
public class LocTextExtension : BaseLocalizeExtension<string>
{
// ---- OLD property
//public string FormatSegment1
//{
// get { return this.formatSegments[0]; }
// set
// {
// this.formatSegments[0] = value;
// this.HandleNewValue();
// }
//}
// ---- NEW DependencyProperty
/// <summary>
/// The <see cref="FormatSegment1" /> dependency property's name.
/// </summary>
public const string FormatSegment1PropertyName = "FormatSegment1";
/// <summary>
/// Gets or sets the value of the <see cref="FormatSegment1" />
/// property. This is a dependency property.
/// </summary>
public string FormatSegment1
{
get
{
return (string)GetValue(FormatSegment1Property);
}
set
{
SetValue(FormatSegment1Property, value);
}
}
/// <summary>
/// Identifies the <see cref="FormatSegment1" /> dependency property.
/// </summary>
public static readonly DependencyProperty FormatSegment1Property = DependencyProperty.Register(
FormatSegment1PropertyName,
typeof(string),
typeof(LocTextExtension),
new UIPropertyMetadata(null));
// ...
}
的BaseLocalizeExtension
類繼承自MarkupExtension
:
public abstract class BaseLocalizeExtension<TValue> : MarkupExtension, IWeakEventListener, INotifyPropertyChanged
當我建,我得到通常"GetValue/SetValue does not exist in current context"
錯誤。我試圖讓BaseLocalizeExtension
類繼承自DependencyObject
,但我收到了很多錯誤。
有沒有辦法在MarkupExtension中使用xaml可綁定的DependencyProperty(或可以綁定的東西)?
謝謝你的提示
[**,只要你的類自DependencyObject派生**,你有一個DependencyProperty標識符來支持你的財產的選擇,從而使它成爲一個依賴項屬性。(http://msdn.microsoft .com/en-us/library/ms753358.aspx) – 2012-03-01 16:39:33
@jberger如果我從DependencyObject派生我的類,如何讓它表現爲MarkupExtension? – 2012-03-02 09:37:20
我不認爲你可以。你必須改變你的模式。你可以嘗試Simon的答案的修改版本。 – 2012-03-02 14:48:54