XAML 如何使用CSS设计Xamarin.Forms中的按钮样式?

kt06eoxx  于 2023-03-10  发布在  其他
关注(0)|答案(1)|浏览(172)

我从xaml文件中添加了一个按钮,如下所示:

<ContentView.Content>
   <Button Image="{Binding Icon}" Text="{Binding Title}" Clicked="ClickEvent" HeightRequest="10"  WidthRequest="10" />
</ContentView.Content>

如何将按钮样式设置为如下所示?

我有CSS文件在我的xamarin项目,但我似乎没有达到按钮图像与它successfully,因为这样的代码没有结果:

.button img {
    height: 50px;
    width: 50px;
}

我目前的一个按钮的结果(可怕),图片是大的方式:

yxyvkwin

yxyvkwin1#

为了能够完全自定义这样的按钮,最好实现自己的Button控件,而不是使用CSS:

XAML语言

<?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="YourApp.Views.SomeRoundImageButton">

  <Frame
    CornerRadius="8">
    <Grid
      RowDefinitions="2*,*">
      <Image
        Grid.Row="0"
        Source="{Binding Icon}"/>
      <Label
        Grid.Row="1"
        TextColor="Blue"
        Text="{Binding Title}"/>      
    </Grid>
    <Frame.GestureRecognizers>
      <TapGestureRecognizer
        Tapped="OnButtonTapped"/>
    </Frame.GestureRecognizers>
  </Frame>

</ContentView>

代码隐藏

using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace YourApp.Views {
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class SomeRoundImageButton : ContentView {

        public string Title {
            get => (string)GetValue(TitleProperty);
            set => SetValue(TitleProperty, value);
        }

        public ImageSource Icon {
            get => (ImageSource)GetValue(IconProperty);
            set => SetValue(IconProperty, value);
        }

        public event EventHandler<EventArgs> ButtonTapped;

        public static readonly BindableProperty TitleProperty = BindableProperty.Create(nameof(Title), typeof(string), typeof(SomeRoundImageButton));
        public static readonly BindableProperty IconProperty = BindableProperty.Create(nameof(Icon), typeof(ImageSource), typeof(SomeRoundImageButton));

        public SomeRoundImageButton() {
            InitializeComponent();
            BindingContext = this;
        }

        private void OnButtonTapped(object sender, EventArgs e) {
            ButtonTapped?.Invoke(this, e);
        }
    }
}

用法

<ContentView.Content>
    <StackLayout>
        <views:SomeRoundImageButton
          Icon="{Binding Icon}"
          Title="{Binding Title}"
          WidthRequest="80"
          HeightRequest="80"
          ButtonTapped="Clicked"/>
    </StackLayout>
</ContentView.Content>

这给了你更多的设计自由,你可以让图像更大或更小,添加更多行的文本到标签,定义CornerRadius的大小,设置各种其他属性...
显然,您需要尝试一下它来找出预期的设计,但我希望这会有所帮助。注意,这只是一种方法。在Xamarin.Forms(和.NET MAUI)中,有许多方法可以实现相同的功能。

相关问题