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

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

问题描述

 < TextBlock的文本={绑定路径= [0]} />
 

 < TextBlock的文本={绑定路径= [的myKey]} />
 

工作正常。但是,有没有办法通过一个变量作为索引键?

 < TextBlock的文本={绑定路径= [{结合Column.Index}]} />
 

解决方案

要处理这种最快捷的方式通常是使用MultiBinding与接受的收集和索引其绑定的IMultiValueConverter:

 < TextBlock.Text>
    < MultiBinding转换器={的StaticResource ListIndexToValueConverter}>
        <装订/> <! - 假定集合DataContext的 - >
        <绑定路径=Column.Index/>
    < / MultiBinding>
< /TextBlock.Text>
 

该转换器可然后执行基于两个值这样的查找

 公共对象转换(对象[]值,类型TARGETTYPE,对象参数,CultureInfo的文化)
{
    如果(values​​.Length 2)
        返回Binding.DoNothing;

    IList的列表=值[0]作为IList的;
    如果(表== NULL ||值[1] == NULL ||!(值[1]为int))
        返回Binding.DoNothing;

    返回表[(int)的值[1]];
}
 

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

or

<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}]} />

解决方案

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天全站免登陆