Xamarin.Forms 按钮的内容 [英] Xamarin.Forms Content of a button

查看:28
本文介绍了Xamarin.Forms 按钮的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向 Xamarin Forms 中的按钮添加自定义内容.

I'm trying to add a custom content to a button in Xamarin Forms.

默认按钮是这样创建的:

By default Button is created like this:

<Button d:DataContext="{d:DesignInstance viewModel:AssessmentItemCategory}"
                        Clicked="Button_OnClicked"
                        Style="{StaticResource CategoryButtonStyle}"
                        Text={Binding Text} />

但我想创建此按钮的自定义内容.通常使用 WPF 我会这样做:

But I would like to create custom content of this button. Normally with WPF I would do it like this:

<Button d:DataContext="{d:DesignInstance viewModel:AssessmentItemCategory}"
          Clicked="Button_OnClicked"
        Style="{StaticResource CategoryButtonStyle}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition Width="20" />
        </Grid.ColumnDefinitions>
        <Label Text="{Binding Text}" Grid.Column="0" TextColor="Black"/>
        <Label Text="-" Grid.Column="1" TextColor="Black"/>
    </Grid>

</Button>

但这不起作用.

我也在寻找 DataTemplate 属性,但没有找到.

I was also looking for a DataTemplate property, but haven't found this.

如何在 Xamarin.Forms 中实现?

How to do it in Xamarin.Forms?

推荐答案

感谢 Paul,

我创建了自己的 UserControl 来处理这个问题

I have created my own UserControl which handles that

这是:

public partial class ContentButton : ContentView
{
    public ContentButton()
    {
        InitializeComponent();
    }

    public event EventHandler Tapped;

    public static readonly BindableProperty CommandProperty = BindableProperty.Create<ContentButton, ICommand>(c => c.Command, null);

    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    private void TapGestureRecognizer_OnTapped(object sender, EventArgs e)
    {
        if(Tapped != null)
            Tapped(this,new EventArgs());
    }
}

并查看代码:

<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="RFA.Wireframes.Controls.ContentButton"
             x:Name="ContentButtonView">
  <ContentView.GestureRecognizers>
    <TapGestureRecognizer Tapped="TapGestureRecognizer_OnTapped" Command="{Binding Source={x:Reference ContentButtonView}, Path=Command}"></TapGestureRecognizer>
  </ContentView.GestureRecognizers>

</ContentView>

这篇关于Xamarin.Forms 按钮的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆