简体   繁体   English

如何将数据传递到XAML中的IValueConverter?

[英]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. 我有一个IValueConverter,它的工作是将BlockId转换为ConditionLabel。 The problem is that my Model object is what has the smarts to do the actual conversion. 问题是我的Model对象具有进行实际转换的智能。 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): 目前,我在这样的ResourceDictionary中创建一个静态资源(稍后在DataTemplate中引用它):

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

The problem is, I need a way to pass my Model object into this converter. 问题是,我需要一种方法将我的Model对象传递给这个转换器。 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. 如果您使用的是MVVM模式,则可以通过在模型的ViewModel中实现转换来解决该问题。

If not, you can take a look at this post on MSDN forums . 如果没有,您可以在MSDN论坛上查看此帖子 (answer from Sam Bent - MSFT) (来自Sam Bent的回答 - MSFT)

The goal is to use multibinding to pass the model to your converter, in this case, pass the DataContext. 目标是使用multibinding将模型传递给转换器,在这种情况下,传递DataContext。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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