my content page is binded to a view model, but now I need to bind some components to a different view model. My problem is that because I have binded the BindingContext of the page to a view model, when I try binding elements to the second view model the {Binding propertyname} statement looks for the property in the view model that is binded to the bindingcontext.
so my question is this: How does one simply bind an element to a view model other then bindingcontext when bindingcontext is set to a different view model?
Things I tried that didn't work
- Defined the second view model. and tried binding through a static resource
code
<ContentPage.Resources>
<ResourceDictionary>
<selectedDeal:DealsMViewModel x:Name="SelectedDeal" x:Key="SelectedDeal"/>
</ResourceDictionary>
</ContentPage.Resources>
code
<Image
x:Name="CompanyImage"
HeightRequest="200"
Aspect="AspectFill"
Source="{Binding Source={StaticResource SelectedDeal}, Path=DealImage}" />
- I've put the image element into a stack layout, set the BindingContext of the StackLayout and
tried binding like this:
code
<Image
x:Name="CompanyImage"
HeightRequest="200"
Aspect="AspectFill"
Source="{Binding DealImage}"/>
There are two ways I made the binding work:
- define the second view model as a property of the first view model that is binded to the BindingContext then implement the image like this
code
<Image
x:Name="CompanyImage"
HeightRequest="200"
Aspect="AspectFill"
Source="{Binding secondViewModel.DealImage}"/>
- in the code behind set the image source programatically.
code
CompanyImage.Source = selectedDeal.DealImage;
But what I really want to achieve is to learn the way of doing this in the XAML part if possible! any help is much appreciated!
question from:
https://stackoverflow.com/questions/65559689/how-to-bind-a-control-to-a-view-model-when-page-binding-context-is-set-to-a-diff 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…