Okay here’s the situation. Net 4 WPF NO Silverlight.
I have several Views that present a datagrid showing the contents of some observable collections e.g.
ObservableCollection<ClassAViewModel> sourceA;
ObservableCollection<ClassBViewModel> sourceB;
ObservableCollection<ClassCViewModel> sourceC;
The collections are populated by a call to the data access layer. I can display this data easily enough with a Usercontrol that contains a datagrid bound to the appropriate collection.
I have
ClassAViewandClassAViewModelto
control display of singleClassA
data,ClassBViewandClassBViewModelto
control display of singleClassBdataClassCViewandClassCViewModelto
control display of singleClassCdata
I also have:
AllClassAViewandAllClassAViewModel
to display a DataGrid with data
relating to allClassAinstances.-
AllClassBViewandAllClassBViewModel
to display a DataGrid with data
relating to allClassBinstances.etc.
Now say that ClassA contains a subset of the ClassB collection and a subset of the ClassC collection etc.
In my resource file I have bound the ViewModels and their Views together in the following manner (vm and vw are the namespaces of where they are) :
<DataTemplate DataType="x:Type vm:ClassAViewModel}">
<vw:ClassAView/>
</DataTemplate>
Now what I was hoping to do was use an AllClassBView or AllClassBViewModel within the ClassAView to display the subset of ClassB instances that relate to it.
What is the best way to call up this data?
Can I re-use the AllClassBView UserControl to display a subset of the ClassB ObservableCollection and what is the best way of doing this?
I don’t want to place any code within the ClassAView.cs file only within the ClassAView.xaml or ClassAViewModel.
Should I just add a new property to the AllClassBView and use that to filter the list? For example within ClassBViewModel where I generate the list of ClassBViewModels (for use in the DataGrid) I can use:
if(this.ClassA_Id!=0)
{
List<ClassBViewModel> all = (from ClassB in this.DataRepository.GetClassBs().Where(x=>x.ClassA_Id == this.ClassA_Id) select new ClassBViewModel()).ToList();
}
else
{
List<ClassBViewModel> all = (from ClassB in this.DataRepository.GetClassBs() select new ClassBViewModel()).ToList();
}
this.sourceB= new ObservableCollection<ClassBViewModel>(all);
Well I’ve cracked it.
My problem may not have come across as very clear.
Whether my solution is good practice or not I don’t know.
What I have done is as follows:
I placed an extra property into the
AllClassBViewModelthat allows me to filter its list ofClassBViewModelsto those that relate toClassA.So now when the
AllClassBViewModelbuilds its list ofClassBViewModelsit can now filter them by:I added a property and field to my ClassAViewModel that were of the AllClassBViewModel type.
I then added an entry to an
AllClassBViewinto theClassAViewthat had a data context bound to theAllClassBVMproperty withinClassAViewModel.No all I have to do is check through the command binding.