页面加载时MVVM加载模型数据

时间:2017-07-03 09:57:59

标签: c# wpf xaml mvvm datagrid

通过使用this blog post正确实现MVVM [可能]作为示例,我设法将数据显示在我的DataGrid上。

请参阅my previous question for history

唯一的事情是当我在我的ViewModel上执行ListCampaignsCommand时,DataGrid只绑定到我的数据,我目前通过Button命令执行此操作:

<!-- 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>

我的ViewModel(可能比它应该做的更多......该示例不涉及使用MVVM与EF数据事物进行交互)获取数据:

// 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);
}

当我尝试在Loaded={Binding ListCampaignsCommand}上添加<Page ...>时,我收到了一条非常神秘的错误消息:

  

抛出异常:PresentationFramework.dll中的'System.Windows.Markup.XamlParseException'

     

其他信息:'为'System.Windows.Data.Binding'提供价值引发异常。行号“10”和行位置“7”。

该行号和位置是Loaded来电的位置。

如何让页面在打开时加载数据?

1 个答案:

答案 0 :(得分:2)

  

如何让页面在打开时加载数据?

如何在视图模型的构造函数中调用ListCampaigns()方法?

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

    //the rest of your code...
}