Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass data into an IValueConverter in XAML?

Tags:

c#

wpf

xaml

I have an IValueConverter whose job it is to convert a BlockId to a ConditionLabel. The problem is that my Model object is what has the smarts to do the actual conversion. My code looks like this so far...

public class BlockIdToConditionLabelConverter : IValueConverter
{
    private Model _model;

    public BlockIdToConditionLabelConverter(Model model)
    {
        _model = model;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int blockId = (int)value;
        return _model.BlockIdToConditionLabel(blockId);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Binding.DoNothing;
    }
}

At the moment, I create a static resource in a ResourceDictionary like this (and later refer to it in a DataTemplate):

<local:BlockIdToConditionLabelConverter
    x:Key="_blockIdToConditionLabelConverter" />

The problem is, I need a way to pass my Model object into this converter. How would I do that?

Thanks.

like image 560
devuxer Avatar asked Jul 12 '09 16:07

devuxer


1 Answers

This is a classic problem with value converters.

If you are using MVVM pattern, you can solve that problem by implementing the conversion inside the ViewModel of your model.

If not, you can take a look at this post on MSDN forums. (answer from Sam Bent - MSFT)

The goal is to use multibinding to pass the model to your converter, in this case, pass the DataContext.

like image 81
decasteljau Avatar answered Sep 23 '22 23:09

decasteljau