wpf 绑定到索引器 [英] wpf bind to indexer

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

问题描述

<TextBlock Text="{Binding Path=[0]} />

<TextBlock Text="{Binding Path=[myKey]} />

工作正常.但是有没有办法将变量作为索引键传递?

works fine. But is there a way to pass a variable as indexer key?

<TextBlock Text="{Binding Path=[{Binding Column.Index}]} />

推荐答案

处理此问题的最快方法通常是将 MultiBinding 与 IMultiValueConverter 一起使用,该 IMultiValueConverter 接受集合及其绑定的索引:

The quickest way to handle this is usually to use a MultiBinding with an IMultiValueConverter that accepts the collection and the index for its bindings:

<TextBlock.Text>
    <MultiBinding Converter="{StaticResource ListIndexToValueConverter}">
        <Binding /> <!-- assuming the collection is the DataContext -->
        <Binding Path="Column.Index"/>
    </MultiBinding>
</TextBlock.Text>

然后转换器可以根据这两个值进行查找,如下所示:

The converter can then do the lookup based on the two values like this:

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    if (values.Length < 2)
        return Binding.DoNothing;

    IList list = values[0] as IList;
    if (list == null || values[1] == null || !(values[1] is int))
        return Binding.DoNothing;

    return list[(int)values[1]];
}

这篇关于wpf 绑定到索引器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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