具有多个参数的转换器 [英] Converter With Multiple Parameters
问题描述
如何在Windows Phone 7应用程序中使用具有多个参数的转换器?
How does one use a converter with Multiple parameters in a Windows Phone 7 Application?
推荐答案
转换器始终实现 IValueConverter 。这意味着调用转换或 ConvertBack 传递一个附加参数。该参数是从XAML中提取的。
Converters always implement IValueConverter. That means a call to Convert or ConvertBack passes a single additional parameter. That parameter is extracted from the XAML.
正如Hitesh Patel所建议的那样,只要您有一个定界符,就可以阻止您在该参数中添加多个值以后将它们分开,但是您不能使用逗号分隔XAML!
As Hitesh Patel suggests there is nothing to stop you putting more than one value into the parameter, so long as you have a delimiter to separate them out later, but you cannot use a comma as that delimits the XAML!
例如
<TextBlock Text="{Binding Path=ReleaseDate, Mode=OneWay,
Converter={StaticResource MyConverter},
ConverterParameter=Param1|Param2}" />
转换器
Converter
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (!string.IsNullOrEmpty(parameterString))
{
string[] parameters = parameterString.Split(new char[]{'|'});
// Now do something with the parameters
}
}
注意,我没有检查它是否查看管道 |字符在XAML中应该是有效的(应该是),但是如果不是,则选择另一个不冲突的字符。
.Net的更高版本不需要最简单的 Split
版本的字符数组,因此您可以改用以下字符:
Later versions of .Net do not require a character array for the simplest version of Split
, so you can use this instead:
string[] parameters = parameterString.Split('|');
附录:
eBay使用的技巧几年前在网址中使用的方法是使用QQ分隔网址中的数据。文本数据中自然不会出现double-Q。如果您曾经为避免使用编码器而无法避免编码问题的文本定界符而苦恼,请使用QQ ...但这将无法使用split(它需要单个字符,但很高兴知道):)
Addendum:
A trick eBay used to use in urls, years ago, was to delimit data in the URL with QQ. A double-Q does not naturally occur in text data. If you ever get stuck for a text delimiter that will avoid encoding issues just use QQ... This will not work with split though (which requires single characters, but nice to know) :)
这篇关于具有多个参数的转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!