Reputation: 2851
How can I bind the padding of a stack layout to a value in a ViewModel?
<StackLayout x:Name="AddressStack" Padding="54.5,0,0,0" >
If the device is a phone I want to reduce the padding to 34.5,0,0,0
In the ViewModel I currently have what's below, just unsure how to wire it up correctly
private double _padding;
public double Padding
{
get
{
return _padding;
}
set
{
if(Device.Idiom == TargetIdiom.Phone)
{
_padding = 34.5;
}
if(Device.Idiom == TargetIdiom.Tablet)
{
_padding = 54.5;
}
}
}
Either that, or I could use something similar to how I set the font based on the platform:
<Label.FontFamily>
<OnPlatform x:TypeArguments="x:String">
<On Platform="iOS" Value="HelveticaNeue-Roman" />
<On Platform="Android" Value="HelveticaNeue-Roman.otf#HelveticaNeue-Roman" />
</OnPlatform>
</Label.FontFamily>
Upvotes: 1
Views: 2599
Reputation: 12169
Before I answer your question, please read the official doc.
Not recommended way, since it should not belong to ViewModel
:
Thickness _padding;
public Thickness Padding
{
get => _padding;
set
{
if(Device.Idiom == TargetIdiom.Phone)
_padding = new Thickness (34.5);
if(Device.Idiom == TargetIdiom.Tablet)
_padding = new Thickness (54.5);
}
}
But why to put it int he ViewModel when you can define it in XAML itself?
<StackLayout x:Name="AddressStack">
<StackLayout.Padding>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="Android" Value="0,20,0,0" />
<On Platform="iOS" Value="0,30,0,0" />
</OnPlatform>
</StackLayout.Padding>
</StackLayout>
or
<StackLayout x:Name="AddressStack">
<StackLayout.Padding>
<OnIdiom x:TypeArguments="Thickness">
<OnIdiom.Phone>
<OnPlatform x:TypeArguments="Thickness" iOS="0,20,0,0" Android="0,20,0,0" WinPhone="0,20,0,0" />
</OnIdiom.Phone>
<OnIdiom.Tablet>
<OnPlatform x:TypeArguments="Thickness" iOS="0,30,0,0" Android="0,30,0,0" WinPhone="0,30,0,0" />
</OnIdiom.Tablet>
</OnIdiom>
</StackLayout.Padding>
</StackLayout>
More about Thickness.
Upvotes: 4