开发者

Filling WPF DataGrid in C# with a Dictionary <String,String>

I want to fill my DataGr开发者_运维百科id in C# with a Dictonary. I already set my Dictionary as the ItemsSource of the DataGrid. But no data is displayed... I also set AutoGenerateColumns to true. Where is the mistake? Thanks in advance


Try to specify the columns explicitly:

<DataGrid.Columns>
    <DataGridTextColumn Header="Key" Binding="{Binding Key}" />
    <DataGridTextColumn Header="Value" Binding="{Binding Value}" />
</DataGrid.Columns>


The following works for me. You dont need to set columns explicitly.

XAML

<Window x:Class="DictionaryDataGridDemo.SingleDictView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:DictionaryDataGridDemo"
        Title="SingleDictView"
        Width="525"
        Height="350">
    <Window.DataContext>
        <local:SingleDictViewModel />
    </Window.DataContext>
    <Grid>
        <DataGrid HorizontalAlignment="Stretch"
                  VerticalAlignment="Stretch"
                  AutoGenerateColumns="True"
                  ItemsSource="{Binding MyDictionary}">
            <!--<DataGrid.Columns>
                <DataGridTextColumn Header="Key" Binding="{Binding Key}" />
                <DataGridTextColumn Header="Value" Binding="{Binding Value}" />
            </DataGrid.Columns>-->
        </DataGrid>
    </Grid>
</Window>

ViewModel

using System.Collections.Generic;

namespace DictionaryDataGridDemo
{
    public class SingleDictViewModel
    {
        public Dictionary<double, string> MyDictionary { get; set; }

        public SingleDictViewModel()
        {
            MyDictionary = new Dictionary<double, string>();
            MyDictionary.Add(100, "A100");
            MyDictionary.Add(200, "B200");
            MyDictionary.Add(300, "C300");
        }
    }
}


Make sure that AutoGenerateColumns is set to False.

    <DataGrid
              AutoGenerateColumns="False"
              ItemsSource="{Binding MyDictionary}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Key" Binding="{Binding Key}" />
            <DataGridTextColumn Header="Value" Binding="{Binding Value}" />
        </DataGrid.Columns>
    </DataGrid>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜