e使顶部带有标签的ImageButton可单击

时间:2020-04-24 09:20:27

标签: xaml xamarin.forms

因此,我在XAML中遇到了Imagebuttons的问题。 我通常会从Photoshop渲染背景图像,然后在各处使用此按钮,然后在上面添加一个标签,说明其功能: enter image description here

这很重要,部分来自此代码:

<!--Grid for button-->
<Grid Grid.Row="1" >
      <ImageButton
           x:Name="btn_register_mainpage"
           Source="btn_emptydummy.png" BackgroundColor="#00000000"/>
      <Label
          FontFamily="arial"
          TextColor="#272727"
          Text="Profil erstellen" 
          HorizontalOptions="Center" 
          VerticalOptions="Center"/>
</Grid>

现在,这很好用,除非您要单击它。 如您所见,我给按钮起了一个名字,我现在可以在代码中捕获该名字并委托单击它:

btn_register_mainpage.Clicked += async delegate
{
      await Navigation.PushAsync(new Screen_EditInformation());
};

但是,这仅在用户单击按钮时才起作用-但在标签上则不起作用,因为它位于顶部且没有分配点击。

因此,我所能做的就是将相同的click事件分配给两个对象(标签和图像按钮),但这似乎很不寻常。

使自定义图像作为按钮并在其顶部具有可单击标签的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以将GestureRecognizers添加到Xamarin.Forms中的任何控件。您可以在网格布局中添加一个

YourView.xaml

<Grid Grid.Row="1" >
    <Grid.GestureRecognizers>
        <TapGestureRecognizer
            Tapped="OnTapGestureRecognizerTapped"
            NumberOfTapsRequired="1" />
    </Grid.GestureRecognizers>
    <ImageButton
        x:Name="btn_register_mainpage"
        Source="btn_emptydummy.png" BackgroundColor="#00000000"/>
    <Label
        FontFamily="arial"
        TextColor="#272727"
        Text="Profil erstellen" 
        HorizontalOptions="Center" 
        VerticalOptions="Center"/>
</Grid>

YourView.xaml.cs

private void OnTapGestureRecognizerTapped(object sender, EventArgs e)
{
    Navigation.PushAsync(new Screen_EditInformation());
}

答案 1 :(得分:0)

您可以在标签上添加 TapGestureRecognizer

<Grid Grid.Row="1" >

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>

            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="40"/>
            </Grid.RowDefinitions>

            <ImageButton
                Clicked="Button_Clicked"
                Grid.Row="0"
                        x:Name="btn_register_mainpage"
                         BackgroundColor="LightBlue"/>
            <Label
                Grid.Row="0"
                        FontFamily="arial"
                        TextColor="#272727"
                        Text="Profil erstellen" 
                        HorizontalOptions="Center" 
                        VerticalOptions="Center">

                <Label.GestureRecognizers>
                    <TapGestureRecognizer
            Tapped="Button_Clicked"
            NumberOfTapsRequired="1" />
                </Label.GestureRecognizers>

            </Label>
        </Grid>