WPF DataGrid binding don’t work caliburn micro

bindingcaliburncaliburn.microdatagridwpf

I can't understand why it does not work..

This is my class

public class Article : Screen
{
    public string Code { get; set; }
    public string Description{ get; set; }
    public decimal Cost{ get; set; }
    public decimal Price{ get; set; }
}

This is XAML code of DataGrid:

    <DataGrid Height="211" HorizontalAlignment="Left" 
        Margin="12,31,0,0" VerticalAlignment="Top" Width="521" 
        AutoGenerateColumns="False" ItemsSource="{Binding List}">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=Code}" Header="Code" />
            <DataGridTextColumn Binding="{Binding Path=Description}" Header="Description" />
            <DataGridTextColumn Binding="{Binding Path=Cost}" Header="Cost" />
            <DataGridTextColumn Binding="{Binding Path=Price}" Header="Price" />
        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Button" Height="39" HorizontalAlignment="Left" 
            Margin="223,262,0,0" VerticalAlignment="Top" Width="110"
            x:Name="AllArticles"/>

And this is my viewmodel

[Export(typeof(IShell))]
public class ArtsViewModel : Screen
{
    public List<Article> List = new List<Article>();

    public void AllArticles()
    {
        Recover recover = new Recover();  //a model called Recover
        List = recover.Import().Articles; //return a List of Article
        NotifyOfPropertyChange("List");
    }    
}

WHY THE DATAGRID DON'T WORK ?

Best Answer

To enable the binding conventions in Caliburn.Micro, you normally use the x:Name property in your XAML. If you, instead of explicitly binding the List property to ItemsSource of your DataGrid, use the name convention like this:

<DataGrid x:Name="List" Height="211" HorizontalAlignment="Left" 
    Margin="12,31,0,0" VerticalAlignment="Top" Width="521" 
    AutoGenerateColumns="False">

I believe the subsequent bindings should work as desired.

Oh, and you also need to make List a property instead of a field:

public List<Article> List { get; private set; }

If you want to make sure that modifications to List are properly reflected in your data grid, you should also make your List property an IObservableCollection with a backing field:

private IObservableCollection<Article> _list;
public IObservableCollection<Article> List { 
    get { return _list; }
    set {
        _list = value;
        NotifyOfPropertyChange(() => List);
    }
}
Related Topic