I have the following xaml: What is needed that the following xaml must be filled dynamic at runtime, but how? The MainWorkspaceViewModel has a property named "View". This property is of type object, so I can set every view in it.
<UserControl x:Class="DesignerWorkspace.Views.MainWorkspaceView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:DesignerWorkspace.Views"
xmlns:vm="clr-namespace:DesignerWorkspace.ViewModels"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<ContentControl Content="{Binding View}"/>
</Grid>
</UserControl>
There are countless ways to do this. First you have to identify if you are using any toolkit that does this for you. After identifying just check how this toolkit was set up and how it is used.
There is a very simple way to do this without any toolkit and the one I am going to show you so that you understand how it works.
note that my example is how to create from a new one, it may not be your case, but it's just to understand (feel free to create a new one and see how it works)
first create a ViewModelBase that implements INotifyPropertyChanged, preferably make this abstract class ViewModelBase class
then create your MainViewModel, have it inherit the ViewModelBase, and create a property for it to be assigned its ViewModels
you should note that the
MainViewModel
has an overridden method of theViewModelBase
(Navigate), it is this method that will be used to open other ViewModels from a simple parameter, a string with the name of the ViewModel that wants to opennow you add to your
MainWindow
your content, in my example, a menu and the content that will be populated with the ViewModelsCreate your views. Example:
Now in the app.xaml file let's say which ViewModel belongs to which UserControl
to open a View from another view use the following:
Edit: I forgot to say, your ViewModel must have at least one constructor (empty) so no problem occurs
The minimum would be to add a context that has the view and updates on property changed.
From somewhere else in the code you can then manage the displayed view by setting the new view.
Here is a simplistic implementation with missing checks you may want to add.