我創建了一個簡單的MVVM wpf項目。基本想法是顯示有關客戶年收入和他與各銀行的貸款的數據。帶有usercontrol的WPF列表框作爲ItemTemplate DataTemplate綁定問題
該模型包括2個類,財務和FinancialLoans。 視圖模型分爲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已經與它金融用戶Ccontrol真實的datacontext綁定到FinancialVM和FinancialLoan用戶使用datacontext控制綁定到FinancialLoanVM。
問題是面子,是用Listbox。我已經將它作爲模板使FinancialLoans用戶控件作爲Items,但綁定的數據不會被注入到FinancialLoanUC DataContext中。 我想訣竅都是在listboxitem datatemplate的一部分。 任何想法,我可以如何使這項工作?
<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>