Robert Robert - 1 month ago 11
C# Question

WPF Datagrid binding does not show values

I am total begginer with WPF and I try to make binding to datagrid in WPF

here is XAML code

<Grid x:Name="LayoutRoot">
<Grid HorizontalAlignment="Left" Height="440" VerticalAlignment="Top" Width="632">
<DataGrid HorizontalAlignment="Left" Height="420" Margin="10,10,0,0" VerticalAlignment="Top" Width="603" ItemsSource="{Binding Source=MailCollection}" AutoGenerateColumns="False">
<DataGridTextColumn Header="id" Binding="{Binding Id}"/>
<DataGridTextColumn Header="nazwa" Binding="{Binding Name}"/>

Here is MailTpl class

public class MailTpl
public string Id { get; set; }
public string Name { get; set; }

And here is how I do binding

public partial class WindowDataGridTest : Window
ObservableCollection<MailTpl> _MailCollection = new ObservableCollection<MailTpl>();

public ObservableCollection<MailTpl> MailCollection { get { return _MailCollection; } }

public WindowDataGridTest()
_MailCollection.Add(new MailTpl { Id= "abbb", Name = "badfasdf" });
_MailCollection.Add(new MailTpl { Id = "asasdfasdfdf", Name = "basdfasdfaa" });

// Insert code required on object creation below this point.

I don't know why it does not work. Any clues? Grid shows no values.


Just an advice for the future.

Visual studio -> Options -> Debugging -> Output Window -> WPF Trace Settings. Here you can set the level of verbosity and see important information about data binding in Ouptut window. It saved me hours.

Now the reson. You declared MailCollection as public property of the Window but binding is made against DataContext by default.

So, you have two ways:

this.DataContext = _MailCollection

and change binding a little to


or just change binding to this:

ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=MailCollection}"

I also recommend this pdf binding cheat sheet. It lacks some WPF 4.5 features but still useful.