wpf Datagrid绑定 Dictionary

 数据源格式:Dictionary<int, List<string>>

1.通过xaml设置

1  <DataGrid x:Name="dg" ItemsSource="{Binding Dic}" AutoGenerateColumns="False">
2             <DataGrid.Columns>
3                 <DataGridTextColumn Header="id" Binding="{Binding Key}"/>
4                 <DataGridTextColumn Header="Name" Binding="{Binding Value[0]}"/>
5                 <DataGridTextColumn Header="Name" Binding="{Binding Value[1]}"/>
6                 <DataGridTextColumn Header="Name" Binding="{Binding Value[2]}"/>
7             </DataGrid.Columns>
8         </DataGrid>
View Code

 2.通过代码设置

DataGridTextColumn column = new DataGridTextColumn(); column.Header = "name4"; column.Binding = new Binding("Value[3]"); dg.Columns.Add(column);

       <DataGrid x:Name="dg" ItemsSource="{Binding Dic}" AutoGenerateColumns="False">
           <DataGrid.Columns>
             <DataGridTextColumn Header="id" Binding="{Binding Key}"/>
           </DataGrid.Columns>
       </DataGrid>


        private Dictionary<int, List<string>> dic;

        public Dictionary<int, List<string>> Dic
        {
            get { return dic; }
            set { dic = value; }
        }

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
            Dic = new Dictionary<int, List<string>>();
            Dic.Add(1, new List<string> { "a", "b", "c", "5" });
            Dic.Add(2, new List<string> { "d" });
            Dic.Add(3, new List<string> { "e", "f" });

            int count = 0;
            foreach (List<string> lst in Dic.Values)
            {
                if (lst.Count > count)
                {

                    for (int i = count; i < lst.Count; i++)
                    {
                        DataGridTextColumn column = new DataGridTextColumn();
                        column.Header = "name" + i;
                        column.Binding = new Binding(string.Format("Value[{0}]", i));
                        dg.Columns.Add(column);
                    }
                    count = lst.Count;
                }
            }
        }

  

 

转载于:https://www.cnblogs.com/zany-hui/articles/7623874.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值