Kilazur
Kilazur

Reputation: 3188

Can a markup extension be aliased?

The markup extension that brought me to ask this is Catel's LanguageBinding.

I was until now using Infralution's localization assembly, which works more or less the same way.

Catel:

<TextBlock Text="{LanguageBinding MyText}"/>

Infralution:

<TextBlock Text="{Resx MyText}"/>

But as you can see, the markup extension is way shorter to write, thus less prone to typos.

So I wanted to know if there was any way to be able to use LanguageBinding with another markup extension word, like:

Ideal:

<TextBlock Text="{LB MyText}"/>

I'm well aware of readability issues and such, it's an example.

Upvotes: 0

Views: 186

Answers (2)

cscmh99
cscmh99

Reputation: 2781

You can inherit MarkupExtension to create your own custom Binding tag

[MarkupExtensionReturnType(typeof(object))]
public class LBBinding : MarkupExtension
{
    private Binding _binding = new Binding();

    public Binding Binding
    {
        get { return _binding; }
        set { _binding = value; }
    }

    public PropertyPath Path
    {
        get { return _binding.Path; }
        set { _binding.Path = value; }
    }



<TextBox Text="{customBinding:LBBinding Path=DummyString}"></TextBox>

You should also override ProvideValue method from MarkupExtension. This method will be trigger whenever WPF perform the actual binding. Use the IServiceProvider to get back your DependencyObject (Control) and the DependencyProperty (Your binding property). Then you can do all the magic you want with those 2 information.

    public override object ProvideValue(IServiceProvider provider)
    {
       var service = (IProvideValueTarget)provider.GetService(typeof(IProvideValueTarget));

Upvotes: 0

wingerse
wingerse

Reputation: 3796

That's not possible to do directly in XAML but you can derive a class from LanguageBinding and use it. Here's an example for shortening the StaticResource Markup Extension.

class SR : StaticResourceExtension
{
    public SR() {}

    public SR(object resourceKey)
        :base(resourceKey)
    { }
}

Now you need can use something like {local:SR} as an "alias".

Upvotes: 2

Related Questions