You can do this by using ContentView that contains some controls to implement it
And you can add TapGestureRecognizer
for the ContentView.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I need to have a button that I can create using a combination of XAML and C#. The content may vary so I want to create various ControlTemplates which I can them load and modify using C# and then load to the UI. It would be somethng akin to the ImageButton but would have other controls than an Image to show in the UI but still handles stuff like a click event.
You can do this by using ContentView that contains some controls to implement it
And you can add TapGestureRecognizer
for the ContentView.
@Lloyd Sheen , bellow you will find one example using MAUI template selector.
You can easily adapt it to our needs. Basically, use the TemplateSelector to define at runtime the template that will controls how your button will draw on the screen.
You can use complex templates, like an image and a combo box, for example. I used a similar solution before, and it was fine to me.
Hope it helps:
https://dev.to/davidortinau/making-a-tabbar-or-segmentedcontrol-in-net-maui-54ha
The follow is the code that I used to get a clickable label.
XAML:
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyDataGrid.LabelClickable">
<VerticalStackLayout>
<Label x:Name="theLabel"
Text="Welcome to .NET MAUI!"
VerticalOptions="Center"
HorizontalOptions="Center">
<Label.GestureRecognizers>
<TapGestureRecognizer NumberOfTapsRequired="1" Tapped="LabelClicked"></TapGestureRecognizer>
</Label.GestureRecognizers>
</Label>
</VerticalStackLayout>
</ContentView>
C#
namespace MyDataGrid;
public partial class LabelClickable : ContentView
{
public LabelClickable()
{
InitializeComponent();
}
public event EventHandler ClickLabelAction;
private void LabelClicked(object sender, TappedEventArgs e)
{
ClickLabelAction?.Invoke(this, e);
}
public string TheText
{
get => (string)GetValue(TheTextProperty);
set => SetValue(TheTextProperty, value);
}
public static readonly BindableProperty TheTextProperty =
BindableProperty.Create(
nameof(TheText),
typeof(string),
typeof(LabelClickable),
null,
propertyChanged: TheTextChanged
);
public Label theActualLabel
{
get { return theLabel; }
}
private static void TheTextChanged(BindableObject bindable, object oldValue, object newValue)
{
LabelClickable labelClickable = (LabelClickable)bindable;
labelClickable.theLabel.Text = (string)newValue;
}
}