I’m still new in .NET MAUI so I still have some problems with basic concepts and best practices. Currently I’m struggling a bit with ContentPresenter
.
So I have a custom component (ContentView
) with ControlTemplate
that uses ContentPresenter
. Let us name this CustomControl.xaml
<ContentView>
<ContentView.ControlTemplate>
<ControlTemplate>
<ContentPresenter />
</ControlTemplate>
</ContentView.ControlTemplate>
</ContentView>
Obviously I’m using MVVM so when I want to use CustomControl
in a view I do this:
<ContentPage>
<local:CustomControl>
<Button Text="Click me" Command="{Binding DoSomethingCommand}" />
</local:CustomControl>
</ContentPage>
where DoSomethingCommand
is defined in my view model.
And this works perfectly fine, awesome! But what if I want to use multiple ContentPresenter
s in my CustomControl
? As far as I know, I should bind content of ContentPresenter
like this:
<ContentView>
<ContentView.ControlTemplate>
<ControlTemplate>
<ContentPresenter Content="{TemplateBinding MyContent}" />
</ControlTemplate>
</ContentView.ControlTemplate>
</ContentView>
Of course I’ve defined BindableProperty
in my code-behind file. And now I’m using my CustomControl
like this:
<ContentPage>
<local:CustomControl>
<local:CustomControl.MyContent>
<Button Text="Click me" Command="{Binding DoSomethingCommand}" />
</local:CustomControl.MyContent>
</local:CustomControl>
</ContentPage>
And my button shows up exactly where it should, but… there is absolutely no effect when clicking on it 🙁
I searched for a solution and I found out that I can use it like that:
<Button Text="Click me" Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodels:MyViewModel}}, Path=DoSomethingCommand}" />
And that indeed works, but it looks awful and I don’t understand it at all 🙁 Could anyone please help me understand why this simple binding to my command doesn’t work? Maybe I can/should modify somehow my CustomControl
?
smalec is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.