Issue
I'm working on a Xamarin.Forms project. I have a ViewModel for displaying a list of objects, and another for editing the objects. In my ListViewModel, I have a Command that takes a selected object and ideally sends it to the EditViewModel. I am getting an error when trying to build the project that says...
Views\EditObjectPage.xaml(9,10): XamlC error XFC0004: Missing default constructor for "MobileApp.ViewModels.EditViewModel"
This is the starting point of my offending code in my Views\EditObjectPage.xaml
.....
x:Class="MobileApp.Views.EditObjectPage"
xmlns:viewmodel="clr-namespace:MobileApp.ViewModels">
<!--Binding Context-->
<ContentPage.BindingContext>
<viewmodel:EditViewModel /> //offending line
</ContentPage.BindingContext>
In the code behind I have a constructor that takes an object from a command in my ListViewModel (Note: I have tried adding an empty default constructor but nothing changed)
namespace MobileApp.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class EditObjectPage : ContentPage
{
public EditObjectPage(Object object)
{
InitializeComponent();
}
}
}
The command in my ListViewModel
public ICommand EditObjectCommand { get; set; } //declaration of property
public ListViewModel()
{
...........
EditObjectCommand = new Command(async (o) => await EditObject(o));
}
private async Task EditObject(object o)
{
SelectedObject = o as Object; //SelectedObject is a working property
await Application.Current.MainPage.Navigation.PushAsync(new
EditObjectPage(SelectedObject);
}
And my EditViewModels Constructor is
public EditViewModel(Object object)
{
_modifiedObject = object; //_modifiedObject is a private property of this class
....
}
I am new to MVVM and Xamarin, and am considering just trying to make my edit and add views and viewmodels the same by just overloading the constructor in the code behind, but I don't actually know if that would work. I realize that this might be a spaghetti code way of doing things, so any input or links would be much appreciated.
Solution
The issue here is the the xaml lines:
<ContentPage.BindingContext>
<viewmodel:EditViewModel /> //offending line
</ContentPage.BindingContext>
use the default constructor for the view model. The easiest way to solve this is to move the creation of the ViewModel insto the View constructor
namespace MobileApp.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class EditObjectPage : ContentPage
{
private EditViewModel _model = null;
public EditObjectPage(Object obj)
{
InitializeComponent();
_model = new EditViewModel(obj);
this.BindingContext = _model;
}
}
}
Answered By - Marco Beninca
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.