你如何将数据传递到XAML的的IValueConverter? [英] How do you pass data into an IValueConverter in XAML?
问题描述
我有一个的IValueConverter其工作是一个BLOCKID转换为ConditionLabel。问题是,我的模型对象是具有智慧做实际的转换。我的代码看起来像这样,到目前为止...
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;
}
}
目前,我创建了一个静态资源ResourceDictionary中像这样的(后来是指它在一个DataTemplate):
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" />
现在的问题是,我需要一种方法来我的Model对象传递到该转换器。我会怎么做呢?
The problem is, I need a way to pass my Model object into this converter. How would I do that?
感谢。
推荐答案
这是一个经典的问题,价值转换器。
This is a classic problem with value converters.
如果您正在使用MVVM模式,你可以通过实现模型的视图模型内的转换解决这个问题。
If you are using MVVM pattern, you can solve that problem by implementing the conversion inside the ViewModel of your model.
如果没有,你可以看看的这个职位上MSDN论坛。 (回答从萨姆特 - MSFT)
If not, you can take a look at this post on MSDN forums. (answer from Sam Bent - MSFT)
的目标是使用multibinding到模型传递到您的转换器,在这种情况下,通过在DataContext
The goal is to use multibinding to pass the model to your converter, in this case, pass the DataContext.
这篇关于你如何将数据传递到XAML的的IValueConverter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!