WPF C# DataGrid的后台动态绑定List<Dictionary<int,double?>>

Li在项目中列数、列标题在运行时才能确定,只能在运行时动态绑定。

前端代码:

<DataGrid x:Name="DgView"/>

后台代码:

    List<Dictionary<uint, double?>> results;//数据源,uint对应列,数据来源省略
    string header;
    foreach (KeyValuePair<uint, double?> node in results.First())
    {
        DataGridTextColumn column = new();
        Binding binding = new(string.Format("[{0}]", node.Key));
        if (node.Key == 0) //时间
        {
            //内容居中
            Style styleCenter = new();
            Setter setter = new(HorizontalAlignmentProperty, HorizontalAlignment.Center);
            styleCenter.Setters.Add(setter);
            column.ElementStyle = styleCenter;

            header = "时间"; //首列列标题
            binding.StringFormat = timeFormat; //timeFormat = "{0:yyyy-MM-dd HH:mm:ss}"
            binding.Converter = new DouToTime(); //数据源为double?转换为表格中DateTime格式
        }
        else
        {
            header = “”; //其他列标题省略
            binding.StringFormat = "{0:f" + Digits + "}";//Digits为小数位数
        }
        column.Binding = binding;
        column.Header = header;
        DgView.Columns.Add(column);
    }
    DgView.AutoGenerateColumns = false;
    DgView.CanUserAddRows = false;
    DgView.ItemsSource = results;

如要多次绑定,重新绑定前加一句:

DgView.Columns.Clear();//重新绑定前应清除列

附DouToTime

[ValueConversion(typeof(DateTime), typeof(Double))]
public class DouToTime : IValueConverter
{
    object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        double d = (double)value;
        DateTime dateTime = new((long)d);
        return dateTime;
    }

    // 只是单向绑定,暂时不用实现
    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值