WPF Binding dynamic converter.

Some time ago I was stuck with problem of using dynamically created converters. So as it turned out the problem could be solved pretty easy – by using MarkupExtension. Create some container like Dictionary and fill it with dynamically created converters, after that create a class like following:

    public class GetConverterExtension : MarkupExtension
    {
        private string _converterName = string.Empty;

        public GetConverterExtension(String converterName)
        {
            if (String.IsNullOrWhiteSpace(converterName))
            {
                throw new ArgumentNullException(nameof(converterName));
            }

            _converterName = converterName;
        }
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return BindingHelper.Instance.Converters[_converterName];
        }
    }

BindingHelper.Instance.Converters is dictionary I talked above.

And that’s all, simply implement appropriate namespace within XAML and use your converters.

Code-behind:

BindingHelper.Instance.Converters.Add("NowDifferenceHours",
                new GenericConverter<DateTime, double>(dt => DateTime.Now.Subtract(dt).TotalHours));

XAML:

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding DateCreated, StringFormat='{}{0:dd-MM-yyyy HH:mm:ss}'}" />
        <TextBlock Margin="6,0,0,0"
                    Text="{Binding DateCreated, Converter={converters:GetConverter 'NowDifferenceHours'}, StringFormat={}{0:[-00.00]}}" />
    </StackPanel>

time_diff

 

Here first textbox shows DateTime from model and second textbox shows difference in hours with current time.

Advertisements

Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s