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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With