1
<Window x:Class="App1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:cust="clr-namespace:App1.Customers"
    Title="Customers"
    Height="525"
    Width="525">

<Window.Resources>
    <DataTemplate DataType="{x:Type cust:CustomerViewModel}">
        <cust:CustomerView />
    </DataTemplate>
</Window.Resources>
<Grid x:Name="MainContent">
    <ContentControl Content="{Binding CurrentViewModel}" />
</Grid>
</Window>

I've declared the datatemplate above in xaml. Over time there could be 20 viewmodels and views the main window might need to know about. I'd rather pass responsibility for adding the datatemplate(s) to the resource dictionary to somewhere else. How can I achieve the above in c#? Just the bit which adds the datatemplate to the resource dictionary

user48408
  • 3,234
  • 11
  • 39
  • 59
  • Why? That's where its supposed to be. Or you could even break it out into a different xaml. Definitely shouldn't be doing it in code. – SledgeHammer Jan 15 '19 at 18:58
  • Thanks for the reply. I tend to agree. Another team member wanted the main window to be much more agnostic about what viewmodels/views it knows about and to just be a container which can be loaded with a usercontrol. I prefer the approach above – user48408 Jan 16 '19 at 09:52
  • With the approach above the window needs to be loaded with resources it may never use. Depending on config from the database the window may only need to display one view or 20 so there is a preference to having a manager of some kind add resources it knows the application will need to the resource dictionary programmatically – user48408 Jan 16 '19 at 10:00
  • Does this answer your question? [Load WPF UI into MVVM application from plug-in assembly](https://stackoverflow.com/questions/12204614/load-wpf-ui-into-mvvm-application-from-plug-in-assembly) – asaf92 Sep 24 '20 at 11:35

0 Answers0