-
Hello, I am building an application using the MVVM pattern. In one of my pages I have a carousel view which I have defined the data template directly in XAML. One of the views in the data template is a button which navigates to another page. I have created a ICommand in the viewmodel which navigates to this page and I am attempting to run the command when the button is clicked. How does the data binding work here? As far as I can tell the data template has no visibility of the parents page BindingContext. If anyone can link me any documentation that covers this or explain where I am going wrong, that would be great. Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
I use RelativeBinding to do this sort of thing. RelativeBinding with Mode=AncestorBindingContext will traverse the view hierarchy looking for the viewmodel by type as defined in AncestorType, and allow you to bind to properties on that viewmodel. Sadly you don't get intellisense using this method, but it does work. |
Beta Was this translation helpful? Give feedback.
-
you could also use x:Reference in the Binding Source and reference the element which has the ViewModel as a BindingContext given you have a ContentPage with a Command in the BindingContext <ContentPage
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:vm="clr-namespace:MyProject.ViewModels"
x:Name="PageSelf"
x:DataType="vm:MyViewModel"
x:Class="MyProject.MyPage"> ... <!-- inside DataTemplate -->
Command="{Binding Source={x:Reference PageSelf}, Path=BindingContext.MyCommand}" |
Beta Was this translation helpful? Give feedback.
you could also use x:Reference in the Binding Source and reference the element which has the ViewModel as a BindingContext
given you have a ContentPage with a Command in the BindingContext
...
<!-- inside DataTemplate --> Command="{Binding Source={x:Reference PageSelf}, Path=BindingContext.MyCommand}"