Search code examples
c#.netwpfdata-bindingexpression-blend

WPF DataGrid binding does not show values


I am a total beginner with WPF and I try to make binding to DataGrid in WPF.

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">
            <DataGrid.Columns>
                <DataGridTextColumn  Header="id" Binding="{Binding Id}"/>
                <DataGridTextColumn  Header="nazwa" Binding="{Binding Name}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Grid>

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" });
        this.InitializeComponent();
        // Insert code required on object creation below this point.
    }
}

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


Solution

  • 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 Output window. It saved me hours.

    Now the reason. 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:

    ItemsSource={Binding}
    

    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.