WPF Listbox with usercontrol as ItemTemplate DataTemplate Binding Issue

I created a simple MVPM wpf project. The main idea is to display data on the client's annual income and on the loans that he has with various banks.

The model consists of 2 classes, financial and financial. ViewModel consists of 2 classes FinancialVM and FinancialLoanVM

The following are the VM classes:

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

}

The user interface has financial control of the user, with it the datacontext bound to FinancialVM and the FinancialLoan User control with the datacontext bound to FinancialLoanVM.

The problem is the face, this is the list. I programmed it that the financialLoans user controls are elements, but the associated data does not fall into the DataContext FinancialLoanUC. I guess the trick is all in the data list part. Any ideas on how I can make this work?

 <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> 
+4
source share
1 answer

Answering my own question, I found that it was not. For FinancialLoanUC, this was in XAML:

 <UserControl.DataContext> <ViewModel:FinancialLoanVM/> </UserControl.DataContext> 

which overloaded the DataContext introduced from FinancialUC. (I believe that it happened that the DataContext was set from a member of the FinancialLoanVM of the observed collection, and then it was replaced with a new instance of the class, as described in XAML)

(From the author)

+4
source

All Articles