Hello,
Welcome to our Microsoft Q&A platform!
. What I want is to bind one VM to two Views like in the picture.
If so, you need to create static ViewModel like following code. For example, you want VIew1 and view2 binding Page1VM
.
public static class ViewModelLocator
{
private static Page1VM _myViewModel = new Page1VM();
public static Page1VM MainViewModel
{
get
{
return _myViewModel;
}
}
}
Here is view1's layout. I delete the ContentPage.BindingContext
, I bind it in the layout background code.
<ContentPage.ToolbarItems>
<ToolbarItem Text="Add" Command="{Binding AddItemCommand}" />
</ContentPage.ToolbarItems>
<ContentPage.Content>
<StackLayout>
<Entry x:Name="Entry" Text="{Binding Cat1, Mode=TwoWay}"
WidthRequest="100"
BackgroundColor="Aqua"/>
<Label Text="{Binding Text1 }" BackgroundColor="Gold" WidthRequest="100"/>
</StackLayout>
</ContentPage.Content>
Here is view1's background code. add BindingContext
like following code.
public partial class AboutPage : ContentPage
{
public AboutPage()
{
InitializeComponent();
BindingContext = ViewModelLocator.MainViewModel;
}
}
In the view2, we need to delete the ContentPage.BindingContext
as well, I also bind it in the layout background code.
<ContentPage.Content>
<StackLayout>
<Label BackgroundColor="Beige" WidthRequest="100" Text="{Binding Cat1, Mode=TwoWay}" />
<Entry Text="{Binding OwnerFirstN , Mode=TwoWay}"/>
<Entry Text="{Binding OwnerLastN, Mode=TwoWay}"/>
<Entry Text="{Binding SicknessCat1, Mode=TwoWay}">
<Entry.BindingContext>
<vm:Page2VM/>
</Entry.BindingContext>
</Entry>
</StackLayout>
</ContentPage.Content>
Here is view2's layout background code.
public partial class Page2 : ContentPage
{
public Page2()
{
InitializeComponent();
BindingContext = ViewModelLocator.MainViewModel;
}
}
Happy new year.
Best Regards,
Leon Lu
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.