You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Infragistics XamDataGrid的AlternateBinding绑定DataItem并动态取字典键?

解决XamDataGrid AlternateBinding动态绑定字典键的MVVM方案

1. 实现动态键值转换的ValueConverter

创建一个实现IValueConverter的转换器,负责将Field的Label(或Name)转换为字典键,并从DailyWorkHours中取出对应的值:

public class DailyWorkHoursConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is YourDataItemType dataItem && parameter is string label)
        {
            // 将Label(如"01")转换为整数键(如1)
            if (int.TryParse(label, out int key))
            {
                if (dataItem.DailyWorkHours.ContainsKey(key))
                {
                    return dataItem.DailyWorkHours[key].AllNightWorkHours;
                }
            }
        }
        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // 如需双向绑定,实现反向转换逻辑
        throw new NotImplementedException();
    }
}

2. 在XAML中配置Field的AlternateBinding

通过RelativeSource绑定到当前的DataRecordPresenter以获取DataItem,并将Field的Label作为转换器参数传入,实现动态字典键绑定:

<UserControl.Resources>
    <local:DailyWorkHoursConverter x:Key="DailyWorkHoursConverter" />
</UserControl.Resources>

<ig:XamDataGrid>
    <ig:XamDataGrid.FieldLayouts>
        <ig:FieldLayout>
            <ig:Field Label="01" Name="Hour01">
                <ig:Field.AlternateBinding>
                    <Binding RelativeSource="{RelativeSource AncestorType={x:Type ig:DataRecordPresenter}}"
                             Path="DataItem"
                             Converter="{StaticResource DailyWorkHoursConverter}"
                             ConverterParameter="{Binding RelativeSource={RelativeSource Self}, Path=Label}" />
                </ig:Field.AlternateBinding>
            </ig:Field>
            <!-- 其他类似Field配置 -->
        </ig:FieldLayout>
    </ig:XamDataGrid.FieldLayouts>
</ig:XamDataGrid>

3. 关键说明

  • 转换器通过ConverterParameter接收Field的Label,动态解析为字典键,无需后台硬编码键值
  • 使用RelativeSource定位DataRecordPresenter获取DataItem,绕开AlternateBinding默认绑定ViewModel的限制
  • 全程无需后台代码干预,完全符合MVVM模式要求

内容的提问来源于stack exchange,提问作者Ho Yin Lin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 23:42:36