I am working on a wpf dll which contains a number of views with accompanying view models to satisfy MVVM.
In my project I have a class which acts as my "view manager" which handles binding each view to their correct view model.
namespace ControlsAndResources
{
public class View
{
private static readonly ViewModelLocator s_viewModelLocator = new ViewModelLocator();
public static readonly DependencyProperty ViewModelProperty = DependencyProperty.RegisterAttached("ViewModel", typeof(string),
typeof(ViewModelLocator), new PropertyMetadata(new PropertyChangedCallback(OnChanged)));
public static void SetViewModel(UserControl view, string value) => view.SetValue(ViewModelProperty, value);
public static string GetViewModel(UserControl view) => (string)view.GetValue(ViewModelProperty);
private static void OnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
UserControl view = (UserControl)d;
string viewModel = e.NewValue as string;
switch (viewModel)
{
case "TestViewModel":
view.DataContext = s_viewModelLocator.TestViewModel;
break;
case "FooViewModel":
view.DataContext = s_viewModelLocator.FooViewModel;
break;
default:
view.DataContext = null;
break;
}
}
}
}
Then I do the binding on each of my xaml declarations (here is one example)
<UserControl x:Class="Foo.Bar.TestView"
...
...
xmlns:controls="clr-namespace:Foo.Bar.ControlsAndResources"
controls:View.ViewModel="TestViewModel"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
...
...
</Grid>
</UserControl>
And this works perfectly. But now what I would like to do is, in my MainView.xaml, include a ContentControl or an ItemControl and use Binding to update my views from my View class. How do I go about doing that?