我是 XAML、WPF 和数据绑定的新手,所以这可能是一个愚蠢的问题。我有一个带有 PurchaseTransactions 集合的 VM,AllTransactionViewModel。我通过资源字典有一个视图,它在 ListView 中呈现集合中的每个 PurchaseTransaction。我可以让视图在主窗口中呈现,但我没有填充数据。
查看 - AllTransactionsView.Xaml:
<UserControl x:Class="BudgetApp.Views.AllTransactionsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" d:DesignWidth="300" Height="97">
<UserControl.Resources>
<CollectionViewSource
x:Key="AllTrans"
Source="{Binding Path=AllTransactions}"/>
</UserControl.Resources>
<ListView
DataContext="{StaticResource AllTrans}"
ItemsSource="{Binding}" >
<ListView.View>
<GridView>
<GridViewColumn
Header="Name"
DisplayMemberBinding="{Binding Path=Name}"
Width="Auto"/>
<GridViewColumn
Header="Transaction Type"
DisplayMemberBinding="{Binding Path=TransactionType}" />
<GridViewColumn
Header="Amount"
DisplayMemberBinding="{Binding Path=Amount}"
/>
</GridView>
</ListView.View>
</ListView>
MainWindowResources.Xaml 中的数据模板:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:BudgetApp.ViewModels"
xmlns:vw="clr-namespace:BudgetApp.Views">
<DataTemplate x:Key="allTransTemplate" DataType="{x:Type vm:AllTransactionViewModel}">
<vw:AllTransactionsView/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:TransactionViewModel}">
<vw:TransactionView />
</DataTemplate>
主窗口.XAML:
<Window x:Class="BudgetApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:BudgetApp.ViewModels"
xmlns:vw="clr-namespace:BudgetApp.Views"
Title="MainWindow" Height="590.717" Width="767.194">
<Window.Resources>
<ResourceDictionary Source="MainWindowResources.xaml"/>
</Window.Resources>
<Grid>
<ContentControl
Content="{Binding AllTransactions}"
ContentTemplate="{StaticResource allTransTemplate}">
</ContentControl>
</Grid>
最后,AllTransactionViewModel 类:
class AllTransactionViewModel: ViewModelBase
{
private BudgetEntities _context;
public AllTransactionViewModel()
{
_context = new BudgetEntities();
AllTransactions = new ObservableCollection<TransactionViewModel>();
GetAllTransactions();
}
public void GetAllTransactions()
{
foreach (var transaction in _context.PurchaseTransactions)
{
AllTransactions.Add(new TransactionViewModel
(
transaction.TransactionDate,
transaction.TransactionType.Description,
transaction.Name,
transaction.Memo,
(double)transaction.Amount,
transaction.IsApproved,
transaction.PurchaseType.Description
)
);
}
}
public ObservableCollection<TransactionViewModel> AllTransactions { get; private set; }
}
我在这里做错了什么?