Reputation: 5055
I have a listbox in WPF that will contain a list of ResultsViewModel
items, however the actual runtime type of these objects could be
CalculateResultsViewModel
, ScenarioResultsViewModel
, GraphResultsviewModel
etc etc, all of which extend the base abstract class ResultsViewModel
.
Each of these view models should be rendered differently in the ListBox
so needs a different DataTemplate
. I can do that just with XAML easy enough. The difficulty is that when the viewmodels are either "processing" or when they have failed", I need them to display a DataTemplate
for "processing" or "errored" which I can only so far do with Triggers
. That however then means I can't use the DataTemplateSelector
or a basic XAML style.
The only solution I can think of (not clean I know) is to set the DataTemplate
programmatically in the SetResult()
method of each viewmodel class, which is what gets called when the processing completes either successfully or with an error. In that DependencyProperty
I can look at the return code and then programatically set the DataTemplate
depending on the sucess/failure result. The only problem is I cannot figure out how to
Obtain a DataTemplate
resource from a ResourceDictionary
just using c# code - bearing in mind Im calling all of this from the viewmodel class, not the window code-behind .xaml.cs file so it doesn't have access to the properties of Window
having only a handle to the viewmodel class, somehow obtain a reference to the ListBoxItem
that contains it and then programmatically set the DataTemplate
on this container.
Can anyone point me in the right direction?
Upvotes: 2
Views: 666
Reputation: 14621
you can take the magic with implicit datatemplates
<ListBox ItemSource={Binding YourResults}>
<ListBox.Resources>
<DataTemplate DataType={x:Type CalculateResultsViewModel}>
<Grid></Grid>
</DataTemplate>
<DataTemplate DataType={x:Type ScenarioResultsViewModel}>
<Grid></Grid>
</DataTemplate>
<DataTemplate DataType={x:Type GraphResultsviewModel }>
<Grid></Grid>
</DataTemplate>
</ListBox.Resources>
</ListBox>
for "processing" or "errored" viewmodels you can specify a adorner overlay in all yout datatemplates (ok but you must use the triggers)
hope this helps
Upvotes: 2