Hello,
Welcome to our Microsoft Q&A platform!
From this doc, we can see passing constructor arguments only support basic types, so you couldn't pass Model MyModel
by this way. And x:Object
couldn't be converted. If you still want to pass value by XAML, you could try to pass basic types or add a property to the ViewModel, refer to the following code:
Basic Types
<ContentPage.BindingContext>
<VM:MainPageVM >
<x:Arguments>
<x:String>4567</x:String>
<x:String>123</x:String>
</x:Arguments>
</VM:MainPageVM>
</ContentPage.BindingContext>
<StackLayout>
<!--test the value-->
<Button Text="{Binding MyModel.Name}" HorizontalOptions="Center" VerticalOptions="Center" Clicked="Button_Clicked"></Button>
<Label Text="{Binding MyModel.ID}"></Label>
</StackLayout>
VM
public class MainPageVM
{
public MainPageVM()
{
}
public MyModel MyModel { get; set; }
public MainPageVM(String titleName,String TitleId)
{
MyModel = new MyModel();
MyModel.Name = titleName;
MyModel.ID = TitleId;
}
}
Add a property to the ViewModel
VM
public class MainPageVM
{
MyModel _myModel;
public event PropertyChangedEventHandler PropertyChanged;
public MainPageVM()
{
}
public MyModel MyModel
{
set
{
if (_myModel != value)
{
_myModel = value;
OnPropertyChanged("MyModel");
}
}
get
{
return _myModel;
}
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Xaml
<ContentPage.BindingContext>
<VM:MainPageVM MyModel="{x:Static VM:App.ModelNow}">
</VM:MainPageVM>
</ContentPage.BindingContext>
static model
public static MyModel ModelNow { get; set; } = new MyModel { Name = "1111", ID = "AAAA"};//add a static model in APP to test
Best Regards,
Wenyan Zhang
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.