如何为DataGrid WPF绑定NameValueCollection?

时间:2019-04-05 12:59:49

标签: c# .net datagrid

我应该使用哪种集合将NameValue集合转换为可绑定到GridView?直接执行操作无效。

NameValueCollection GetCollection1()
        {
            NameValueCollection collection = new NameValueCollection();
            collection.Add("Sam", "Dot Net Perls");
            collection.Add("Bill", "Microsoft");
            collection.Add("Bala", "White House");
            collection.Add("Samy", "IBM");

            return collection;
        }



<DataGrid Name="dgCollection" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Key" Binding="{Binding Key}">
                    </DataGridTextColumn>
                    <DataGridTextColumn Header="Value" Binding="{Binding Value}" />
                </DataGrid.Columns>
            </DataGrid>

dgCollection.ItemsSource = GetCollection1();

enter image description here

是否有任何自定义控件都支持这种Collection,例如SfDataGrid,RadGrid,Xceed.DataGrid

1 个答案:

答案 0 :(得分:0)

当要在数据网格中显示集合时,应将集合绑定到数据网格。 这可以通过绑定Datagrid的ItemSource属性来完成。可以像这样将其绑定在后面的代码中

dataGrid1.ItemsSource = Customer.GetSampleCustomerList();

如果要在XAML中绑定集合的值。您应该将GetCollection1设置为属性,而不是返回方法。

<DataGrid Name="dgCollection" AutoGenerateColumns="False" ItemSource="{Binding GetCollection1"}>
        <DataGrid.Columns>
            <DataGridTextColumn Header="Key" DisplayMemberPath="{Binding Path=Key}">
            </DataGridTextColumn>
            <DataGridTextColumn Header="Value" DisplayMemberPath="{Binding Path=Value}" />
        </DataGrid.Columns>
        </DataGrid>

有关ItemSource property

的信息,请参见链接。

要显示数据,您应该使用DisplayMemberPath属性。