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
3 Answers
26
votes
9
votes
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");
}
}
}
2
votes
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>