1

I would like to assign a view / view model mapping at run time as opposed to compile time. Lets say there is a common page in my application that I would like to swap the view out based on the selected view model. It seems like the way to achieve this is the following code.

<Page.Resources>
    <DataTemplate DataType="{x:Type model:ViewModelExampleA}">
        <view:ViewExampleA />
    </DataTemplate>
</Page.Resources>
<Grid>
    <ContentControl Content={Binding SelectedPageViewModel}/>
</Grid>

However, this seems to require knowing the types at compile time since the types for the DataTemplate are directly written out in the xaml. What if I would like to extend this such that at run time, new types could be registered and displayed by this page?

I basically have what is outlined in the code above. I got a little stalled out in trying to figure out how to make this dynamic, any nudges in the right direction would help!

sdub0800
  • 139
  • 1
  • 9
  • You could generate a resource dictionary defining your templates as a string and xamlreader parse it or save to disk and xamlreader load it. The contents could be built using reflection. You could use metadata to identify which is related to what. And you could generate your c# and compile on the fly. Or use iron python for your code and dynamically load it. It's quite hard work doing Wpf with iron python in my experience though. – Andy Feb 03 '23 at 19:41

0 Answers0