MVVM load model data when the Page loads

2019-08-18 06:42发布

问题:

By implementing MVVM [possibly] correctly using this blog post as an example, I managed to get my data showing on my DataGrid.

See my previous question for history.

The only thing is that the DataGrid only binds to my data when I execute ListCampaignsCommand on my ViewModel which I'm currently doing through a Button Command:

<!-- Pages\ManageCampaigns.xaml -->
<Button Name="btnRefresh" Grid.Column="0" Command="{Binding ListCampaignsCommand}"
    Style="{StaticResource TitleButtonLink}" Margin="20,4,0,0">Refresh List
</Button>

<DataGrid x:Name="campaignDataGrid" AutoGenerateColumns="False" EnableRowVirtualization="True"
            ItemsSource="{Binding Campaigns}" Grid.Row="1" 
            RowDetailsVisibilityMode="VisibleWhenSelected">
    <DataGrid.Columns>
        <DataGridTextColumn x:Name="idColumn" Binding="{Binding Id}"
                            Header="#" Width="SizeToCells" />
        <DataGridTextColumn x:Name="clientColumn" Binding="{Binding Client}"
                            Header="Client" Width="SizeToHeader" />
        <DataGridTextColumn x:Name="dateSentColumn" Binding="{Binding DateSent}"
                            Header="Date" Width="SizeToCells" />
        <DataGridTextColumn x:Name="nameColumn" Binding="{Binding Name}" Header="Name" Width="SizeToCells"/>
        <DataGridTextColumn x:Name="emailAddressColumn" Binding="{Binding EmailAddress}" Header="Email Address" Width="SizeToCells"/>
    </DataGrid.Columns>
</DataGrid>

My ViewModel (which probably does more than it should... The example didn't involve using MVVM to interact with EF data things) gets the data:

// CampaignViewModel
private readonly ObservableCollection<Campaign> _campaigns
    = new ObservableCollection<Campaign>();

public IEnumerable<Campaign> Campaigns
{
    get { return _campaigns; }
}

public ICommand ListCampaignsCommand
{
    get { return new DelegateCommand(ListCampaigns); }
}
public void ListCampaigns()
{
    using (ApplicationDbContext db = new ApplicationDbContext())
    {
        var Campaigns = db.Campaigns.Where(x => x.Deleted == false);
        foreach (var c in Campaigns)
        {
            AddToCampaigns(c);
        }
    }
}
private void AddToCampaigns(Campaign campaign)
{
    if (!_campaigns.Contains(campaign))
        _campaigns.Add(campaign);
}

When I tried adding Loaded={Binding ListCampaignsCommand} on my <Page ...> I got a very cryptic error message:

Exception thrown: 'System.Windows.Markup.XamlParseException' in PresentationFramework.dll

Additional information: 'Provide value on 'System.Windows.Data.Binding' threw an exception.' Line number '10' and line position '7'.

That line number and position is where the Loaded call is.

How can I get the Page to load the data when it opens?

回答1:

How can I get the Page to load the data when it opens?

How about calling your ListCampaigns() method in the constructor of the view model?

public class CampaignViewModel
{
    public CampaignViewModel()
    {
        ListCampaigns();
    }

    //the rest of your code...
}