How to simplify your Converter binding syntax, and when you probably wouldn't use it...

Converter as a Markup Extension

I was stuck on a gnarly WPF problem the other day (to do with inheritance context for 3rd party controls and UI elements not in the logical or visual tree)*. Well fortunately for me, I happen to be just an IM away from some the smartest WPF people in ANZ, not the least of which is Mabster

Here's a (trivialised) snippet that represents the code I sent him:

<TextBlock
    Text="{Binding Foo, Converter={local:DebugConverter}}" />

His first comment was 'Wait, the converter is a MarkupExtension?'

It sure is - It's something I've done since I read this article by Dr Wpf a couple of years ago...

The converter itself looks like this:

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;

namespace SomeNamespace
{
    public class DebugConverter : MarkupExtension, IValueConverter
    {
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            //  No conversion needed - just want to break here to see what's coming into the Binding
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

Basically, if the converter object is a markup extension, then you remove the ceremony for declaring an instance somewhere in the xaml resources, and then having to refer to it by key when you use it - you can just create a fresh instance inline in the Binding...

In other words, we change from:

<Window.Resources>
    <local:DebugConverter x:Key="debugConverter" />
</Window.Resources>

<TextBlock
    Text="{Binding Foo, Converter={StaticResource debugConverter}}" />

to (as we saw earlier):

<TextBlock
    Text="{Binding Foo, Converter={local:DebugConverter}}" />

It's certainly cleaner xaml, for only a minor investment in the code (we just need to implement an override for ProvideValue)... so what's the catch?

Well, if we have a converter being used in multiple places across a view, and from a performance perspective, we just wanted to instantiate (and re-use) a single instance, then this isn't going to work for us.

But in the 99 times out of 100 where we don't care about that, this is a useful tool to have in your bag of tricks.

Enjoy :)


* Never did solve it - had to chuck in some code-behind, but that's not the end-of-the-world :)

xaml wpf
Posted by: Ian Randall
Last revised: 16 Apr, 2011 02:05 a.m.

Comments

Gtjkguyjhff
Gtjkguyjhff
27 Apr, 2012 02:25 p.m.

Изумительная альтернатива химическим стиральным средствам — мыльные орехи. Это орешки индийского дерева, которые имеют моющие и противогрибковыми характеристиками. В отличии от стандартных стиральных порошков, орехи не содержат вредных веществ для здоровья и не вызывают аллергии. Мыльные орехи применяется для уборки в доме, стирки, мытья посуды, а также чистки украшений. Лучше ознакомиться с товаром и купить, можно заглянув в магазин эко товаров для красоты и здоровья. CHANDI интернет магазин косметики. Мыльные орехи.


Ремонт холодильников у станции метро Аэропорт

Immocouct
Immocouct
13 May, 2012 10:36 p.m.

http://gin-seng.ru/upload/shop1/1/7/4/item174/smallshopitemscatalogimage174.jpg

Женьшень — многолетнее травянистое растение семейства Аралиевых. В основном используется как адаптоген и в качестве общетонизирующего укрепляющего средства. В Китае и Корее женьшень используют в приготовлении пищи. Восточная медицина утверждает, что препараты женьшеня продлевают жизнь и молодость. Женьшень и его производные стимулируют центральную нервную систему, уменьшая общую слабость, утомляемость и сонливость, повышают артериальное давление, умственную и физическую работоспособность, стимулируют половую функцию, снижают содержание холестерина и глюкозы в крови, активируют деятельность надпочечников.

продажа водка со змеей

водка со змеёй в україні купити

женьшень красная книга

herba epimedii

Your Comments

Used for your gravatar. Not required. Will not be public.
Posting code? Indent it by four spaces to make it look nice. Learn more about Markdown.

Preview