多参数转换器

问题描述 投票:23回答:5

有谁知道如何在Windows Phone 7应用程序中使用带有多个参数的转换器?

提前致谢。

c# silverlight windows-phone-7 xaml ivalueconverter
5个回答
49
投票

转换器始终实现IValueConverter。这意味着调用ConvertConvertBack会传递一个额外的参数。该参数是从XAML中提取的。

正如Hitesh Patel建议没有什么可以阻止你在参数中放置多个值,只要你有一个分隔符将它们分开,但是你不能使用逗号分隔XAML!

EG

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的字符数组,因此您可以使用它:

string[] parameters = parameterString.Split('|');

附录:

多年前曾经在网址中使用的一个技巧eBay是用QQ划分网址中的数据。双Q在文本数据中不会自然出现。如果你遇到了一个文本分隔符,这将避免编码问题,只需使用QQ ...虽然这不适用于拆分(这需要单个字符,但很高兴知道):)


10
投票

您始终可以从DependecyObject类派生,并根据需要添加任意数量的DependencyProperties。例如:

ExampleConverter.cs

public class ExampleConverter : DependencyObject, IValueConverter
{
    public string Example
    {
        get => GetValue(ExampleProperty).ToString();
        set => SetValue(ExampleProperty, value);
    }
    public static readonly DependencyProperty ExampleProperty =
        DependencyProperty.Register("Example", typeof(string), typeof(ExampleConverter), new PropertyMetadata(null));

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //Do the convert
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后在XAML中:

ExampleView.xaml

<ResourceDictionary>
    <converters:ExampleConverter x:Key="ExampleConverter" Example="{Binding YourSecondParam}"/>
</ResourceDictionary>
...
<TextBlock Text="{Binding Path=ReleaseDate, Mode=OneWay,
                    Converter={StaticResource ExampleConverter}, 
                    ConverterParameter={Binding YourFirstParam}}" />

9
投票

虽然上述答案可能是可行的,但它们似乎过于复杂。只需在XAML代码中使用带有适当IMultiValueConverterMultiBinding即可。假设您的ViewModel具有属性FirstValueSecondValueThirdValue,它们分别是intdoublestring,有效的多转换器可能如下所示:

C#

public class MyMultiValueConverter : IMultiValueConverter {
  public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
    int firstValue = (int)values[0];
    double secondValue = (double)values[1];
    string thirdValue = (string)values[2];

    return "You said " + thirdValue + ", but it's rather " + firstValue * secondValue;
  }

  public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) {
    throw new NotImplementedException("Going back to what you had isn't supported.");
  }
}

XAML

<TextBlock.Text>
  <MultiBinding Converter="{StaticResource myNs:MyMultiValueConverter}">
    <Binding Path="FirstValue" />
    <Binding Path="SecondValue" />
    <Binding Path="ThirdValue" />
  </MultiBinding>
</TextBlock.Text>

既然它既不需要使用ProvideValue所需的MarkupExtension方法,也不需要在转换器内部使用DependencyObject的规格,我相信这是最优雅的解决方案。


2
投票

这可以使用System.Windows.Markup.MarkupExtensiondocs)完成。

这将允许您将值传递给转换器,该转换器可用作参数或返回值,例如:

public class CustomNullToVisibilityConverter : MarkupExtension, IValueConverter
{
    public object NullValue { get; set; }
    public object NotNullValue { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null) return NullValue;

        return NotNullValue;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

用法:

...
Visibility="{Binding Property, Converter={cnv:CustomNullToVisibilityConverter NotNullValue=Visible, NullValue=Collapsed}}" />
...

请务必在.xaml中引用转换器的命名空间。


1
投票

如果您的输入不能使用字符串,并且您有多个参数(不是绑定)。你可以传递一个集合。定义一个类型,以避免某些UI编辑器与数组的问题:

public class BrushCollection : Collection<Brush>
{
}

然后使用该集合添加XAML

                <TextBox.Background >
                    <Binding Path="HasInitiativeChanged" Converter="{StaticResource changedToBrushConverter}">
                        <Binding.ConverterParameter>
                            <local:BrushCollection>
                                <SolidColorBrush Color="{DynamicResource ThemeTextBackground}"/>
                                <SolidColorBrush Color="{DynamicResource SecondaryColorBMedium}"/>
                            </local:BrushCollection>
                        </Binding.ConverterParameter>
                    </Binding>

                </TextBox.Background>

然后将结果转换为转换器中相应类型的数组:

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {

        BrushCollection brushes = (BrushCollection)parameter;
© www.soinside.com 2019 - 2024. All rights reserved.