How to bind an object to a view programmatically using WinUI3 with C++/WinRT? - c++-winrt

I am using WinUI3 with C++/WinRT and I am trying to bind an object like "User" to a collection like "ListViewItem".
Below you can see the xaml and the code behind creating a list view item and the binding part.
XAML:
<StackPanel>
<Button x:Name="button" Click="button_Click" Content="Add" />
<ListView x:Name="listView" />
</StackPanel>
CPP:
class User : public ::winrt::Microsoft::UI::Xaml::Data::INotifyPropertyChanged
{
public:
User() {}
~User() {}
void Name(const ::winrt::hstring& aName) {
if (mName != aName) {
mName = aName;
mPropertyChanged(*this, ::winrt::Microsoft::UI::Xaml::Data::PropertyChangedEventArgs{ L"Name" });
}
}
::winrt::hstring Name() {
return mName;
}
::winrt::event_token PropertyChanged(::winrt::Microsoft::UI::Xaml::Data::PropertyChangedEventHandler const& aHandler) {
return mPropertyChanged.add(aHandler);
}
void PropertyChanged(::winrt::event_token const& aToken) noexcept {
mPropertyChanged.remove(aToken);
}
private:
::winrt::hstring mName = L"NoName";
event<::winrt::Microsoft::UI::Xaml::Data::PropertyChangedEventHandler> mPropertyChanged;
};
::winrt::Microsoft::UI::Xaml::Controls::ListViewItem CreateLVI() {
::winrt::Microsoft::UI::Xaml::Controls::TextBlock myText;
User myDataObject;
::winrt::Microsoft::UI::Xaml::Data::Binding myBinding;
myBinding.Path(::winrt::Microsoft::UI::Xaml::PropertyPath(L"Name"));
myBinding.Source(myDataObject);
::winrt::Microsoft::UI::Xaml::Data::BindingOperations::SetBinding(myText, ::winrt::Microsoft::UI::Xaml::Controls::TextBlock::TextProperty(), myBinding);
::winrt::Microsoft::UI::Xaml::Controls::ListViewItem lvi;
lvi.Content(myText);
return lvi;
}
MainWindow::MainWindow()
{
InitializeComponent();
}
void MainWindow::button_Click(::winrt::Windows::Foundation::IInspectable const& sender, ::winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e)
{
listView().Items().Append(CreateLVI());
}
But it doesnt work, the user's name doesnt show in the list view item. The list view item is created tho.

Related

How to two way bind to a UserControl DependencyProperty?

I am making a custom slider called scalar_slider using a UserControl. I would like to two way bind one of it's DependencyProperty.
The problem is that the value changes made inside scalar_slider are not updated back to the parent's view model vm which correctly implements INotifyPropertyChanged. I assume the problem has to do with how I am setting the binding in MainPage.xaml.
// MainPage.xaml
<local:scalar_slider scalar_value="{x:Bind vm.my_scalar_value Mode=TwoWay}" />
// scalar_slider.xaml
<UserControl
x:Class="transformations.scalar_slider"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:transformations"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<StackPanel>
<TextBox Text="{x:Bind scalar_value, Mode=TwoWay}"/>
<Slider Value="{x:Bind scalar_value, Mode=TwoWay}"/>
</StackPanel>
</UserControl>
//scalar_slider.idl
namespace transformations
{
[default_interface]
runtimeclass scalar_slider : Windows.UI.Xaml.Controls.UserControl, Windows.UI.Xaml.Data.INotifyPropertyChanged
{
scalar_slider();
static Windows.UI.Xaml.DependencyProperty scalar_valueProperty;
Single scalar_value;
}
}
//scalar_slider.h
namespace winrt::transformations::implementation
{
struct scalar_slider : scalar_sliderT<scalar_slider>
{
scalar_slider();
static Windows::UI::Xaml::DependencyProperty scalar_valueProperty();
static void scalar_valueProperty(Windows::UI::Xaml::DependencyProperty value);
float scalar_value();
void scalar_value(float value);
winrt::event_token PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const& handler);
void PropertyChanged(winrt::event_token const& token) noexcept;
template <class T>
void update_value(hstring const& property_name, T & var, T value)
{
if (var != value)
{
var = value;
raise_property_changed(property_name);
}
}
private:
event<Windows::UI::Xaml::Data::PropertyChangedEventHandler> m_property_changed;
void raise_property_changed(hstring const& property_name)
{
m_property_changed(*this, Windows::UI::Xaml::Data::PropertyChangedEventArgs(property_name));
}
static Windows::UI::Xaml::DependencyProperty m_scalar_value_property;
float m_scalar_value = 0.0f;
};
}
//scalar_slider.cpp
namespace winrt::transformations::implementation
{
scalar_slider::scalar_slider()
{
InitializeComponent();
}
winrt::event_token scalar_slider::PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const& handler)
{
return m_property_changed.add(handler);
}
void scalar_slider::PropertyChanged(winrt::event_token const& token) noexcept
{
m_property_changed.remove(token);
}
Windows::UI::Xaml::DependencyProperty scalar_slider::m_scalar_value_property = Windows::UI::Xaml::DependencyProperty::Register(
L"scalar_value",
winrt::xaml_typename<float>(),
winrt::xaml_typename<winrt::transformations::scalar_slider>(),
Windows::UI::Xaml::PropertyMetadata{ nullptr }
);
Windows::UI::Xaml::DependencyProperty scalar_slider::scalar_valueProperty()
{
return m_scalar_value_property;
}
void scalar_slider::scalar_valueProperty(Windows::UI::Xaml::DependencyProperty value)
{
m_scalar_value_property = value;
}
float scalar_slider::scalar_value()
{
return m_scalar_value;
}
void scalar_slider::scalar_value(float value)
{
update_value(L"scalar_value", m_scalar_value, value);
}
}
About your code, I find the get and set function of scalar_slider property you write are not correct in scalar_slider.cpp, you can change them like below code.
You can also read XAML custom (templated) controls with C++/WinRT to understand better.
float scalar_slider::scalar_value()
{​
return winrt::unbox_value<float>(GetValue(m_scalar_value_property));​
}​
​
void scalar_slider::scalar_value(float value)​
{​
SetValue(m_scalar_value_property, winrt::box_value(value));​
m_property_changed(*this, Windows::UI::Xaml::Data::PropertyChangedEventArgs(L"scalar_value"));​
}

tabbed page causing more time to load the application

I am trying develop a xamarin app which has tabbed pages.
I have 3 main tabs.Each page viewmodel contructor has 3-5 Api calls.So its taking more time(20s) to load my app(for opening).
mainpage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Myapplication.Views.MenuPage"
xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
xmlns:b="clr-namespace:Prism.Behaviors;assembly=Prism.Forms"
prism:ViewModelLocator.AutowireViewModel="True"
xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
xmlns:views="clr-namespace:Dyocense.Views"
android:TabbedPage.ToolbarPlacement="Bottom"
android:TabbedPage.IsSwipePagingEnabled="False"
>
<views:A Title="A" Icon="dsjsdsd_18dp.png" ></views:A>
<views:B Title="B" Icon="askjasa.png"></views:B>
<views:C Title="C" Icon="abc.png"></views:C>
<views:D Title="D" Icon="abc.png"></views:D>
</TabbedPage>
How to load only first tab(A) detail page on app loading and rest of the pages on tab changing.
A solution is to make the heavy pages load their content in a lazy manner, only when their tab becomes selected. This way, since these pages are now empty when TabbedPage is created, navigating to the TabbedPage suddenly becomes very fast!
1.create a behavior for the TabbedPage page, called ActivePageTabbedPageBehavior.
class ActivePageTabbedPageBehavior : Behavior<TabbedPage>
{
protected override void OnAttachedTo(TabbedPage tabbedPage)
{
base.OnAttachedTo(tabbedPage);
tabbedPage.CurrentPageChanged += OnTabbedPageCurrentPageChanged;
}
protected override void OnDetachingFrom(TabbedPage tabbedPage)
{
base.OnDetachingFrom(tabbedPage);
tabbedPage.CurrentPageChanged -= OnTabbedPageCurrentPageChanged;
}
private void OnTabbedPageCurrentPageChanged(object sender, EventArgs e)
{
var tabbedPage = (TabbedPage)sender;
// Deactivate previously selected page
IActiveAware prevActiveAwarePage = tabbedPage.Children.OfType<IActiveAware>()
.FirstOrDefault(c => c.IsActive && tabbedPage.CurrentPage != c);
if (prevActiveAwarePage != null)
{
prevActiveAwarePage.IsActive = false;
}
// Activate selected page
if (tabbedPage.CurrentPage is IActiveAware activeAwarePage)
{
activeAwarePage.IsActive = true;
}
}
}
2.define IActiveAware interface
interface IActiveAware
{
bool IsActive { get; set; }
event EventHandler IsActiveChanged;
}
3.create a base generic abstract class called LoadContentOnActivateBehavior
abstract class LoadContentOnActivateBehavior<TActivateAwareElement> : Behavior<TActivateAwareElement>
where TActivateAwareElement : VisualElement
{
public DataTemplate ContentTemplate { get; set; }
protected override void OnAttachedTo(TActivateAwareElement element)
{
base.OnAttachedTo(element);
(element as IActiveAware).IsActiveChanged += OnIsActiveChanged;
}
protected override void OnDetachingFrom(TActivateAwareElement element)
{
(element as IActiveAware).IsActiveChanged -= OnIsActiveChanged;
base.OnDetachingFrom(element);
}
void OnIsActiveChanged(object sender, EventArgs e)
{
var element = (TActivateAwareElement)sender;
element.Behaviors.Remove(this);
SetContent(element, (View)ContentTemplate.CreateContent());
}
protected abstract void SetContent(TActivateAwareElement element, View contentView);
}
4.the specialized LazyContentPageBehavior
class LazyContentPageBehavior : LoadContentOnActivateBehavior<ContentView>
{
protected override void SetContent(ContentView element, View contentView)
{
element.Content = contentView;
}
}
then we can use in xaml like this:
<TabbedPage>
<TabbedPage.Behaviors>
<local:ActivePageTabbedPageBehavior />
</TabbedPage.Behaviors>
<ContentPage Title="First tab">
<Label Text="First tab layout" />
</ContentPage>
<local:LazyLoadedContentPage Title="Second tab">
<ContentPage.Behaviors>
<local:LazyContentPageBehavior ContentTemplate="{StaticResource ContentTemplate}" />
</ContentPage.Behaviors>
<ContentPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key="ContentTemplate">
<!-- Complex and slow to render layout -->
<local:SlowContentView />
</DataTemplate>
</ResourceDictionary>
</ContentPage.Resources>
</local:LazyLoadedContentPage>
</TabbedPage>
we moved the ContentPage complex layout to become a DataTemplate.
Here's the custom LazyLoadedContentPage page which is activation aware:
class LazyLoadedContentPage : ContentPage, IActiveAware
{
public event EventHandler IsActiveChanged;
bool _isActive;
public bool IsActive
{
get => _isActive;
set
{
if (_isActive != value)
{
_isActive = value;
IsActiveChanged?.Invoke(this, EventArgs.Empty);
}
}
}
}
SlowContentView do some complex things
public partial class SlowContentView : ContentView
{
public SlowContentView()
{
InitializeComponent();
// Simulating a complex view
...
}
}
you could refer to the link
As a workaround I created a new class extending the Xamarin.Forms.TabbedPage and I send a message every time one of the tabs is clicked (or in general is diplayed)
public enum TabbedPages
{
MyPage1 = 0,
MyPage2 = 1,
MyPage3 = 2,
}
public class BottomBarPage : Xamarin.Forms.TabbedPage
{
protected override void OnCurrentPageChanged()
{
base.OnCurrentPageChanged();
var newCurrentPage = (TabbedPages)Children.IndexOf(CurrentPage);
MessagingCenter.Send<Xamarin.Forms.TabbedPage>(this, newCurrentPage.ToString("g"));
}
}
and then on the view models used for each page loaded when clicking on the tab I subscribe to the message and call my APIs
public class MyPage2ViewModel
{
public MyPage2ViewModel()
{
MessagingCenter.Subscribe<TabbedPage>(this, TabbedPages.MyPage2 .ToString("g"), async (obj) =>
{
//API call
});
}
}

UWP NavigationView hide NavPane on specific "fullscreen" Page

I have very basic NavigationView with frame:
<NavigationView
x:Name="navigationView"
AlwaysShowHeader="False"
SelectionChanged="{x:Bind ViewModel.OnSelectionChanged}">
<Grid>
<Frame x:Name="shellFrame" />
</Grid>
</NavigationView>
And simplest EventHandler:
public async void OnSelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
var item = args.SelectedItem as NavigationViewItem;
// I'm using Prism framework, by the way...
navigationService.Navigate(item.Tag.ToString(), null);
}
I want to get the same as done in Groove Music, when you navigating to Now Playing - NavPane is hiding, and only appbackbutton is available.
My current solution is to catch OnNavigatedTo and OnNavigatedFrom events on my FullscreenPage and change NavigationView.CompactPaneLength and NavigationView.OpenPaneLength:
public override void OnNavigatedTo(NavigatedToEventArgs e, Dictionary<string, object> viewModelState)
{
// private field
// navigationPage = Window.Current.Content as NavigationPage;
navigationPage.NavigationView.IsPaneToggleButtonVisible = false;
navigationPage.NavigationView.CompactPaneLength = 0;
navigationPage.NavigationView.OpenPaneLength = 0;
}
public override void OnNavigatingFrom(NavigatingFromEventArgs e, Dictionary<string, object> viewModelState, bool suspending)
{
navigationPage.NavigationView.IsPaneToggleButtonVisible = true;
navigationPage.NavigationView.CompactPaneLength = 64;
navigationPage.NavigationView.OpenPaneLength = 320;
}
It's works as expected, but there is some agly freezes, when NavigationView is "collapsing".
Maybe there is a better solution?
I want to get the same as done in Groove Music, when you navigating to Now Playing
The NavigationView was displayed in the MainPage's Frame and it contained ContentFrame that used to display FirstPage and SecondPage. If you want to display PlayPage and hide NavigationView, the better way is that displayed PlayPage in the MainPageFrame just like the following picture.
When you back from PlayPage to MainPage, the NavigationView will display automatically, and you need not handle the complex animation for NavigationView. Please refer the following code.
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.NavigationMode == NavigationMode.Back)
{
foreach(NavigationViewItemBase item in NvTest.MenuItems)
{
if((string) item.Tag == contentFrame.CurrentSourcePageType.Name)
{
SelectItem = item;
}
}
}
Windows.UI.Core.SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
base.OnNavigatedTo(e);
}
private NavigationViewItemBase selectItem;
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public NavigationViewItemBase SelectItem
{
get
{
return selectItem;
}
set
{
selectItem = value;
OnPropertyChanged();
}
}
private void NvTest_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
var selectedItem = (NavigationViewItem)args.SelectedItem;
string pageName = "App14." + ((string)selectedItem.Tag);
if ((string)selectedItem.Tag == "PlayPage")
{
this.Frame.Navigate(Type.GetType(pageName));
}
else
{
sender.Header = pageName;
Type pageType = Type.GetType(pageName);
contentFrame.Navigate(pageType);
}
}
MainPage.xaml
<Grid>
<NavigationView x:Name="NvTest" SelectionChanged="NvTest_SelectionChanged" SelectedItem="{x:Bind SelectItem,Mode=TwoWay}">
<NavigationView.MenuItems>
<NavigationViewItem Icon="Play" Content="Menu Item1" Tag="SamplePage1" />
<NavigationViewItemSeparator/>
<NavigationViewItem Icon="Save" Content="Menu Item2" Tag="PlayPage" />
<NavigationViewItem Icon="Save" Content="Menu Item3" Tag="SamplePage2" />
</NavigationView.MenuItems>
<Frame x:Name="contentFrame"/>
</NavigationView>
</Grid>
This is code sample.

PropertyChangedCallback is not getting fired during callback when a value in ViewModel is changed

I have a view that uses the SearchBox user control, The SearchBox has two radio buttons to select the search modes - Instant and delayed. I have binded the searchmodes to SearchMode property, and also I have created a custom dependency property for the Search Mode.
View
<controls:SearchBox Grid.Row="0"
HorizontalAlignment="Right"
Margin="2" Width="200"
SearchMode="{Binding DataContext.SearchMode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged }" />
ViewModel.cs
private Mode mSearchMode;
public Mode SearchMode
{
get
{
return mSearchMode;
}
set
{
mSearchMode = value;
NotifyOfPropertyChange();
}
}
// Called when application is restarted.
private void ActivateLastSelectedSearchMode(Mode lastselectedMode)
{
// Sets the last selected mode to the search mode
SearchMode = lastselectedMode;
}
public enum Mode
{
Instant,
Delayed,
}
SearchBox.xaml
<UserControl x:Class = "abc.SearchBox"
DataContext="{Binding RelativeSource={RelativeSource Self}}" >
<UserControl.Resources>
<converters:EnumToBooleanConverter x:Key="EnumToBooleanConverter" />
</UserControl.Resources>
<StackPanel Orientation="Vertical">
<RadioButton Content="{lex:Loc SearchBox:SearchModelInstatOption}"
IsChecked="{Binding Path=SearchMode, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static local:Mode.Instant}}" />
<RadioButton Content="{lex:Loc SearchBox:SearchModeDelayedOption}"
IsChecked="{Binding Path=SearchMode, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static local:Mode.Delayed}}" />
</StackPanel>
</UserControl>
SearchBox.xaml.cs
public partial class SearchBox : UserControl
{
public static DependencyProperty SearchModeProperty =
DependencyProperty.Register(
"SearchMode",
typeof(Mode),
typeof(SearchBox),
new FrameworkPropertyMetadata(default(Mode), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsSearchModeChanged));
static void OnIsSearchModeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var searchBox = obj as SearchBox;
searchBox.SearchMode = (Mode)e.NewValue;
}
public Mode SearchMode
{
get { return (Mode)GetValue(SearchModeProperty); }
set { SetValue(SearchModeProperty, value); }
}
}
I want the OnIsSearchModeChanged() to be fired each time when SearchMode is set during call back i e, ActivateLastSelectedSearchMode() is invoked in ViewModel.cs. I am absolutely clueless..where I am missing, I am unable to achieve success.
//snip
private Mode mSearchMode;
public Mode SearchMode
{
get
{
return mSearchMode;
}
set
{
mSearchMode = value;
NotifyOfPropertyChange(()=>SearchMode); //Change
}
}
does the reflected change make any difference? Other option would be to create a custom convention for your user control
You should create an Event in you View Model and subscribe to it from your code behind.
In your View Model :
public event SearchModeAction SearchModeChanged;
public delegate void SearchModeAction(object sender, EventArgs e);
public void SearchModeHasChanged()
{
SearchModeAction Handler = SearchModeChanged;
if (Handler != null)
{
Handler(this, null);
}
}
private void ActivateLastSelectedSearchMode(Mode lastselectedMode)
{
// Sets the last selected mode to the search mode
SearchMode = lastselectedMode;
SearchModeHasChanged()
}
In your Code Behind :
private void Window_Loaded(object sender, RoutedEventArgs e)
{
((YourViewModelClass)DataContext).SearchModeChanged += OnIsSearchModeChanged;
}
private void OnIsSearchModeChanged(object sender, EventArgs e)
{
var searchBox = obj as SearchBox;
searchBox.SearchMode = (Mode)e.NewValue;
}
This way each time you arrive in your ActivateLastSelectedSearchMode method in your View Model, you will call your OnIsSearchModeChanged method in your View.
Ahh..the reason was the EnumToBooleanConverter.
Though the value of 'parameter' and 'value' was same, There was a difference between their object types as both were referencing to different namespaces. So I created a public enum called 'Mode' and ensured that the 'Instant' and 'Delayed' reference to the same namespace.
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
{
return false;
}
return value.Equals(parameter); // This always returned false despite the values being the same
}

Xamarin Forms: How can I add padding to a button?

I have the following XAML Xamarin.Forms.Button
<Button Text="Cancel" BackgroundColor="#3079a8" TextColor="White" />
I tried to add padding to it via the Padding property but that didn't work. After checking the forums and the docs, I realised there is no padding property in the documentation for Xamarin.Forms.Button (link to the docs)
, is there some other type of quick fix to add just a little bit more padding to a button? A code example would be greatly appreciated.
usage:
<controls:EnhancedButton Padding="1,2,3,4"/>
advantages:
no nasty sideeffects
no problem with alignments
no viewtree uglyness
no view depth incrementation
ios:
[assembly: ExportRenderer(typeof(EnhancedButton), typeof(EnhancedButtonRenderer))]
namespace YOURNAMESPACE.iOS
{
public class EnhancedButtonRenderer : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
UpdatePadding();
}
private void UpdatePadding()
{
var element = this.Element as EnhancedButton;
if (element != null)
{
this.Control.ContentEdgeInsets = new UIEdgeInsets(
(int)element.Padding.Top,
(int)element.Padding.Left,
(int)element.Padding.Bottom,
(int)element.Padding.Right
);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == nameof(EnhancedButton.Padding))
{
UpdatePadding();
}
}
}
}
android:
[assembly: ExportRenderer(typeof(EnhancedButton), typeof(EnhancedButtonRenderer))]
namespace YOURNAMESPACE.Droid
{
public class EnhancedButtonRenderer : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
UpdatePadding();
}
private void UpdatePadding()
{
var element = this.Element as EnhancedButton;
if (element != null)
{
this.Control.SetPadding(
(int)element.Padding.Left,
(int)element.Padding.Top,
(int)element.Padding.Right,
(int)element.Padding.Bottom
);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == nameof(EnhancedButton.Padding))
{
UpdatePadding();
}
}
}
}
pcl:
public class EnhancedButton : Button
{
#region Padding
public static BindableProperty PaddingProperty = BindableProperty.Create(nameof(Padding), typeof(Thickness), typeof(EnhancedButton), default(Thickness), defaultBindingMode:BindingMode.OneWay);
public Thickness Padding
{
get { return (Thickness) GetValue(PaddingProperty); }
set { SetValue(PaddingProperty, value); }
}
#endregion Padding
}
Solution using effects instead of renderers, to allow easy usage for more than one control:
XAML:
<Label Text="Welcome to Xamarin.Forms!" BackgroundColor="Red">
<Label.Effects>
<xamTest:PaddingEffect Padding="20,40,20,40"></xamTest:PaddingEffect>
</Label.Effects>
</Label>
PCL:
[assembly: ResolutionGroupName("ComponentName")]
namespace XamTest
{
public class PaddingEffect : RoutingEffect
{
/// <inheritdoc />
protected PaddingEffect(string effectId) : base($"ComponentName.{nameof(PaddingEffect)}")
{
}
public Thickness Padding { get; set; }
}
}
Android:
[assembly: ResolutionGroupName("ComponentName")]
[assembly: ExportEffect(typeof(XamTest.Droid.PaddingEffect), "PaddingEffect")]
namespace XamTest.Droid
{
public class PaddingEffect : PlatformEffect
{
/// <inheritdoc />
protected override void OnAttached()
{
if (this.Control != null)
{
var firstMatch = this.Element.Effects.FirstOrDefault(d => d is XamTest.PaddingEffect);
if (firstMatch is XamTest.PaddingEffect effect)
{
this.Control.SetPadding((int)effect.Padding.Left, (int)effect.Padding.Top, (int)effect.Padding.Right, (int)effect.Padding.Bottom);
}
}
}
/// <inheritdoc />
protected override void OnDetached()
{
}
}
}
Update:
Padding has been added to the XF Button control in Xamarin.Forms v3.2+
<Button Padding="10,20,10,20" />
Old:
The best way to do it would be to increase the size of the button.
Then align the text as you see fit. Unfortunately it is about the best you can do. It works well if you have your text center aligned. Not so much if its left or right aligned.
you can wrap your button in a StackLayout and add padding to the StackLayout
<StackLayout Padding="10,10,10,10">
<Button Text="Cancel" BackgroundColor="#3079a8" TextColor="White" />
</StackLayout>
In iOS, you can use a simple custom renderer to add a bit of padding to the button:
[assembly: ExportRenderer(typeof(Button), typeof(iOSButtonRenderer))]
namespace My.App.iOS.Renderers.Button
{
/// <summary>
/// A custom renderer that adds a bit of padding to either side of a button
/// </summary>
public class iOSButtonRenderer : ButtonRenderer
{
public iOSButtonRenderer() { }
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
Control.ContentEdgeInsets = new UIEdgeInsets(Control.ContentEdgeInsets.Top, Control.ContentEdgeInsets.Left + 10, Control.ContentEdgeInsets.Bottom, Control.ContentEdgeInsets.Right + 10);
}
}
}
It doesn't work for me in android.
Looking at SetPadding function, I see that the Control has a minimum height of 132 and a minimum width of 242.
I changed the SetPadding function in:
private void SetPadding()
{
var element = Element as ExtendedButton;
if (element != null)
{
Control.SetMinHeight(-1);
Control.SetMinimumHeight(-1);
Control.SetMinWidth(-1);
Control.SetMinimumWidth(-1);
Control.SetPadding(
(int)element.Padding.Left,
(int)element.Padding.Top - 6,
(int)element.Padding.Right,
(int)element.Padding.Bottom - 6);
}
}
The simplest you can do is
<StackLayout Margin="0,20,0,0" Orientation="Horizontal" Spacing="20">
<Switch VerticalOptions="CenterAndExpand" ></Switch>
<Label VerticalOptions="CenterAndExpand" TextColor="White">Remember Me</Label>
<StackLayout HorizontalOptions="FillAndExpand"><Button VerticalOptions="CenterAndExpand" HorizontalOptions="FillAndExpand" Text="Sign In" TextColor="White" BackgroundColor="#5cb85c" ></Button>
</StackLayout>
</StackLayout>
[such a big headache working with xamarin forms :'(]