多参数转换器 [英] Converter With Multiple Parameters

查看:36
本文介绍了多参数转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 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}" />

转换器

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 分隔网址中的数据.双 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆