简体   繁体   中英

How do you pass data into an IValueConverter in 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM