我创建了一个简单的 MVVM wpf 项目。基本思想是显示有关客户的年收入和他在各个银行的贷款的数据。
该模型包括 2 个类,金融和金融贷款。ViewModel 包含 2 个类 FinancialVM 和 FinancialLoanVM
以下是VM类:
namespace WpfTester.ViewModel{
public class FinancialVM
{
public Model.Financial Financial { get; set; }
public ObservableCollection<ViewModel.FinancialLoanVM> FinancialLoanVMs { get; set; }
public FinancialVM()
{
//Fill the models with some sample data
Financial = new WpfTester.Model.Financial { Income = 1950.12 };
Financial.FinancialLoans = new ObservableCollection<Model.FinancialLoan>();
Financial.FinancialLoans.Add(new WpfTester.Model.FinancialLoan { Bank = new Random().Next().ToString() });
Financial.FinancialLoans.Add(new WpfTester.Model.FinancialLoan { Bank = new Random().Next().ToString() });
FinancialLoanVMs = new ObservableCollection<FinancialLoanVM>();
foreach (Model.FinancialLoan financialLoan in Financial.FinancialLoans)
{
FinancialLoanVMs.Add(new ViewModel.FinancialLoanVM { FinancialLoan = financialLoan });
}
} }
public class FinancialLoanVM
{
public Model.FinancialLoan FinancialLoan { get; set; }
public FinancialLoanVM()
{ FinancialLoan = new Model.FinancialLoan(); }
}
}
UI 有一个 Financial User Ccontrol,它的 datacontext 绑定到 FinancialVM,还有一个 FinancialLoan User 控件,datacontext 绑定到 FinancialLoanVM。
问题是面对,是与列表框。我已将其模板化为将 FinancialLoans 用户控件作为项目,但绑定的数据不会注入 FinancialLoanUC DataContext。我想诀窍在于 listboxitem 数据模板的一部分。关于如何使这项工作的任何想法?
<UserControl.DataContext>
<ViewModel:FinancialVM/>
</UserControl.DataContext>
<Grid d:DataContext="{d:DesignInstance Type=ViewModel:FinancialVM}" >
<Grid.RowDefinitions>
<RowDefinition Height="23"/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal">
<TextBlock Text="Income= "/>
<Label Content="{Binding Path=Financial.Income}"/>
</StackPanel>
<ListBox Grid.Row="1" ItemsSource="{Binding Path=FinancialLoanVMs}">
<ListBox.ItemTemplate>
<DataTemplate>
<View:FinancialLoanUC DataContext="{Binding }" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>