.net - wpf 绑定(bind)到索引器

标签 .net wpf xaml data-binding indexer

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

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

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

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

最佳答案

处理此问题的最快方法通常是使用带有 IMultiValueConverter 的 MultiBinding,该 IMultiValueConverter 接受集合及其绑定(bind)的索引:

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

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

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

关于.net - wpf 绑定(bind)到索引器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4511619/

相关文章:

c# - 并行 c# 使用的内核数

.net - 如何确保在数据绑定(bind)的 ListBox 中没有选择任何项目?

c# - 公开在另一个自定义控件的控件模板中定义的自定义控件事件

c# - 删除所有添加到 Canvas 的图像

c# - 在后面的 C# 代码中设置网格列或网格行

XAML 按钮导致 Xamarin 应用程序在启动时崩溃

c# - 在 C# 中一定数量的单词或字符后中断文本的方法?

c++ - 在访问冲突时创建转储文件

c# - 在 Windows Phone 8.1 中制作瘦 BottomAppBar

.net - 处置或不处置 (CA2000)