c# - XAML 索引器数据绑定(bind)

标签 c# wpf xaml data-binding mvvm

我在一个名为 X 的类中有一个 Indexer 属性,假设 X[Y] 给我另一个类型为 Z:

<ContentControl Content="{Binding X[Y]}" ...???

如何在索引器中创建一个DataBinding?如果我执行 {Binding [0]},它会起作用。但是 {Binding X[Y]} 只是将索引器参数作为 Y 的字符串。

更新: Converter 是一个选项,但我有很多带有索引器的 ViewModel 类,但没有类似的集合,所以我负担不起为所有这些创建单独的转换器。所以我只想知道 WPF 是否支持此功能,如何声明 Content=X[Y] 其中 XYDataContext 属性?

最佳答案

我发现实现此目的的唯一方法是通过 MultiBinding和一个 IMultiValueConverter .

<TextBlock DataContext="{Binding Source={x:Static vm:MainViewModel.Employees}">
    <TextBlock.Text>
       <MultiBinding Converter="{StaticResource conv:SelectEmployee}">
           <Binding />
           <Binding Path="SelectedEmployee" />
       </MultiBinding>
    </TextBlock.Text>
</TextBlock>

还有你的转换器:

public class SelectEmployeeConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, 
        object parameter, CultureInfo culture)
    {
        Debug.Assert(values.Length >= 2);

        // change this type assumption
        var array = values[0] as Array;
        var list = values[0] as IList;
        var enumerable = values[0] as IEnumerable;
        var index = Convert.ToInt32(values[1]);

        // and check bounds
        if (array != null && index >= 0 && index < array.GetLength(0))
            return array.GetValue(index);
        else if (list != null && index >= 0 && index < list.Count)
            return list[index];
        else if (enumerable != null && index >= 0)
        {
            int ii = 0;
            foreach (var item in enumerable)
            {
                if (ii++ == index) return item;
            }
        }

        return Binding.DoNothing;
    }

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

关于c# - XAML 索引器数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1792478/

相关文章:

c# - 将 LINQ intersect 函数与非基本类型结合使用

c# - 在 asp.net webforms 上创建单个异步 webmethod 以进行长轮询

c# - 在 Windows 8.1 的 C# XAML 中,如何将样式绑定(bind)到变量?

xaml - 如何删除 MasterDetailPage 上的汉堡菜单图标但保留导航栏

c# - XAML 图像源

javascript - Webpack devserver 代理无法解决 CORS 问题

c# - 将 CancellationToken 传递给任务类构造函数有什么用?

c# - WPF:样式化文本框不显示光标

c# - 后面的wpf绑定(bind)代码

html - 在 WPF 中显示 HTML 内容