MarkupExtension: преобразование простого свойства в DependencyProperty - PullRequest
3 голосов
/ 01 марта 2012

Я использую WPFLocalizationExtension (доступно на CodePlex ) для локализации строк в моем приложении WPF.Это простое MarkupExtension хорошо работает в простых сценариях, таких как:

<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, но получаю массу ошибок.

Есть ли способ использовать привязываемый xaml DependencyProperty (или что-то, что также можно связать) в MarkupExtension?

Спасибо за подсказки

1 Ответ

0 голосов
/ 01 марта 2012

Вместо этого вы можете перейти к присоединенному свойству, это ваш единственный вариант, как я вижу.

, например

public static readonly DependencyProperty FormatSegment1Property = DependencyProperty.RegisterAttached(
        "FormatSegment1", typeof(string), typeof(LocTextExtension), new PropertyMetadata(default(string)));

public static void SetFormatSegment1(DependencyObject element, string value)
{
    element.SetValue(FormatSegment1Property, value);
}

public static string GetFormatSegment1(DependencyObject element)
{
    return (string)element.GetValue(FormatSegment1Property);
}

.

<Window Title="{lex:LocText MyApp:Resources:windowTitle}" lex:LocText.FormatSegment1="{Binding Version}" />
...