I have a own MyContentPage inherited from ContentPage. Inside I use a ContentPresenter and I want to set dynamicaly a Padding via ViewModel.
When I set a fix Padding it works.
<ContentPresenter Padding="60" ../>
When I use the Binding it does not work.
<ContentPresenter Padding="{Binding MyPadding}"../>
How can I bind the Padding value?
I tried for MyPadding string, int and float.
Xaml:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:offline="clr-namespace:Controls.Offline;assembly=Controls"
xmlns:pages="clr-namespace:Controls.Pages"
x:DataType="pages:MyContentPageViewModel"
x:Class="Controls.Pages.MyContentPage2"
Title="MyContentPage2">
<ContentPage.ControlTemplate>
<ControlTemplate>
<Grid RowDefinitions="auto,*">
<offline:OfflineMarkerView Grid.Row="0" />
<ContentPresenter Grid.Row="1"
BackgroundColor="{StaticResource Gray90}"
Padding="{Binding MyPadding}" />
</Grid>
</ControlTemplate>
</ContentPage.ControlTemplate>
</ContentPage>
codebehind:
public partial class MyContentPage2 : ContentPage
{
public MyContentPage2()
{
Shell.SetTitleView(this, new MyIconTitleView());
InitializeComponent();
BindingContext = new MyContentPageViewModel();
}
}
ViewModel:
public partial class MyContentPageViewModel : ObservableObject
{
[ObservableProperty]
private float _myPadding;
public MyContentPageViewModel()
{
MyPadding = 50;
}
}
The Binding for ControlTemplate is a little bit different. You may take a look at docs about MAUI Control templates.
I would like to share two ways of Binding MyPadding property in ViewModel.
Option 1 Use TemplateBinding for ControlTemplates
So we try this,
We use
TemplateBindingto binds to the property of the page. And MyPadding is a property in ViewModel which is set as the BindingContext of the page.Option 2 Use x:reference
You may set the name for page who consumes the ControlTemplates, such as
x:Name="this". When using Binding for Padding, set the Binding Source to the page using x:reference. Then you could easily bind the Padding value to the MyPadding property in ViewModelHere is the screenshot for setting padding as
MyPadding = 50f;,Please let me know if you have any questions.