Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

datagrid

I want to fill my DataGrid 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

like image 584
Caro Avatar asked Mar 05 '11 14:03

Caro


3 Answers

Try to specify the columns explicitly:

<DataGrid.Columns>
    <DataGridTextColumn Header="Key" Binding="{Binding Key}" />
    <DataGridTextColumn Header="Value" Binding="{Binding Value}" />
</DataGrid.Columns>
like image 56
Thomas Levesque Avatar answered Nov 13 '22 13:11

Thomas Levesque


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");
        }
    }
}
like image 34
Jeson Martajaya Avatar answered Nov 13 '22 11:11

Jeson Martajaya


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>
like image 2
icernos Avatar answered Nov 13 '22 12:11

icernos