There is an user control for ContextMenu which will be re-used in other user controls. The problem is the controls which would like to use this Contextmenu needs to create the ContextMenuViewModel and populate its DataContext which is the normal practice.
Is there a way to create a factory for the View so it will be created on the fly and not worried about its data context from the control which is consuming it?
You can use Locator pattern
Ex:
uses of a “Locator” such as:
DataContext="{Binding Main, Source={StaticResource Locator}}">
There is locators created in the application.
<Application x:Class="XXX.App"
xmlns:views="clr-namespace:XXX.Views"
xmlns:vm="clr-namespace:XXX.ViewModels"
StartupUri="MainWindow.xaml"
>
<Application.Resources>
...
<vm:ViewModelLocator x:Key="Locator" />
...
</Application.Resources>
</Application>
The class "Locator":
public class ViewModelLocator
{
private static MainViewModel _main;
/// Initializes a new instance of the ViewModelLocator class.
public ViewModelLocator()
{
_main = new MainViewModel();
}
/// Gets the Main property which defines the main viewmodel.
public MainViewModel Main
{
get
{
return _main;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With