Search code examples
wpfmvvmprismdatacontext

How to set data context for user control with prism wpf?


This my view.xaml:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height=".5*"/>
        <RowDefinition Height="0.5*"/>
    </Grid.RowDefinitions>

    <Grid Grid.Row="0" x:Name="grdFormSearch" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        <local:StudentUserControl HorizontalAlignment="Stretch" Height="100" VerticalAlignment="Stretch"/>
    </Grid>
</Grid>

Above I added a StudentUserControl in view.xaml.

StudentUserControl.xaml.cs:

public partial class StudentUserControl : UserControl
{
   public StudentUserControl(StudentViewModel ViewModel)
   {
       InitializeComponent();
       this.DataContext = ViewModel;
   }
}

StudentViewModel.cs:

public StudentViewModel(IEventAggregator eventAggregator, IUnityContainer container)
{
     _eventAggregator = eventAggregator;
     _container = container;
}

It is throwing an error in xaml, as it's expecting a parameterless constructor!

How to set the DataContext for the UserControl? What is the best approach to do it?


Solution

  • Remove the parameter from the constructor of the view:

    public partial class StudentUserControl : UserControl
    {
        public StudentUserControl()
        {
            InitializeComponent();
        }
    }
    

    It shouldn't be there if you want to be able to create an instance of the view in your XAML markup like you are doing here:

    <local:StudentUserControl HorizontalAlignment="Stretch" Height="100" VerticalAlignment="Stretch"/>
    

    Besides, you shouldn't explicitly set the DataContext of the view in the code-behind anyway. The DataContext should in most cases be inherited from the parent element, i.e. view.xaml in your case, and if you explicitly set the DataContext in the constructor of the view, you break the inheritance.

    If the parent view has no DataContext for some reason, you could use Prism's view model locator to create a view model:

    <UserControl x:Class="WpfApplication1.StudentUserControl"
        ...
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True">
    

    Please refer to the following link for more information about this: http://brianlagunas.com/getting-started-prisms-new-viewmodellocator/