转换器参数--有没有一种方法可以传递一些分隔的列表?

5
基本上,如果我有以下内容:
<TextBlock Text="{Binding MyValue, Converter={StaticResource TransformedTextConverter},
           ConverterParameter=?}" />

如何将某些类型的项目数组作为ConverterParameter传递?我想我可以传递某种分隔列表,但我不确定要使用什么类型的分隔符,或者是否有一种内置的方法来传递参数数组?


你是不是试图将参数作为MyValue的索引使用?为什么不在你的Convert方法中解析它呢? - Berryl
2个回答

9
ConverterParameter 的类型是 object,这意味着当 XAML 被解析时不会有任何隐式转换,如果您传入任何分隔符列表,它将被解释为一个字符串。当然,您可以在转换方法中拆分它。
但是,由于您可能需要更复杂的对象,因此在处理静态值时可以采取两种方法:创建对象数组作为资源并引用它,或使用元素语法直接创建数组,例如:
1:
<Window.Resources>
    <x:Array x:Key="params" Type="{x:Type ns:YourTypeHere}">
        <ns:YourTypeHere />
        <ns:YourTypeHere />
    </x:Array>
</Window.Resources>

... ConverterParameter={StaticResource params}

2:

<TextBlock>
    <TextBlock.Text>
        <Binding Path="MyValue" Converter="{StaticResource TransformedTextConverter}">
            <Binding.ConverterParameter>
                <x:Array Type="{x:Type ns:YourTypeHere}">
                    <ns:YourTypeHere />
                    <ns:YourTypeHere />
                </x:Array>
            </Binding.ConverterParameter>
        </Binding>
    </TextBlock.Text>
</TextBlock>

4

ConverterParameter不是一个依赖属性,因此不能基于绑定。

您可以硬编码一个值,例如用x分隔的参数列表,然后在您的转换器中使用.Split(x),或者您可以使用MultiConverter,它允许您将多个绑定值发送到转换器。

<!-- Not sure the exact syntax, but I'm fairly sure you have 
     to escape the commas -->
<TextBlock Text="{Binding MyValue, 
           Converter={StaticResource TransformedTextConverter},
           ConverterParameter={};@,@|}" />

或者
<TextBlock>
    <TextBlock.Text>
        <MultiBinding Converter="{StaticResource MyMultiConverter}">
            <Binding Path="MyValue" />
            <Binding Path="Parameters" />
        </MultiBinding>
    </TextBlock.Text>
<TextBlock>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接