XAML 如何在.NET MAUI中调整图像大小< Button>

3xiyfsfu  于 2023-03-21  发布在  .NET
关注(0)|答案(3)|浏览(262)

我刚接触.NET Maui和XAML,我正在尝试制作一个简单的按钮菜单。
当我使用时,图像填充了所有的空间,文本标签不显示。按钮是用来显示图标的,但当使用图标时,它们也会被拉伸。
https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/button?view=net-maui-7.0

虽然Button定义了ImageSource属性,该属性允许您在Button上显示图像,但此属性旨在用于在Button文本旁边显示小图标。
下面是代码和结果:

<Button HeightRequest="300"
            WidthRequest="300"
            BorderColor="Blue"
            BorderWidth="3"
            BackgroundColor="Grey"
            Text="TEXT INSIDE BUTTON"
            FontSize="12"
            FontAttributes="Bold"
            ImageSource="https://aka.ms/campus.jpg"
            ContentLayout="Top, 1">

    </Button>

result
我想实现的是一些类似的卡与边界,图像和文字
desired result
NET MAUI文档,Youtube教程等。对XAML相当陌生

snvhrwxg

snvhrwxg1#

似乎没有一个这样的Button控件可以达到你想要的效果。所以你可以使用一个控件来包含图像和文本。然后使用TapGestureRecognizer来处理点击事件。例如:

<Frame HeightRequest="150" WidthRequest="150" BorderColor="Red" Margin="20" >
            <VerticalStackLayout Margin="-10">
                <Image Source="image.png" WidthRequest="100" HeightRequest="100" Margin="-10"/>
                <Label Margin="0" Text="this is text" WidthRequest="100" HeightRequest="50" HorizontalTextAlignment="Center" VerticalTextAlignment="Center"/>
            </VerticalStackLayout>
            <Frame.GestureRecognizers>
                <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
            </Frame.GestureRecognizers>
        </Frame>

Margin属性可用于调整视图的精细位置。
在Page.cs中:

 private void TapGestureRecognizer_Tapped(object sender, TappedEventArgs e)
    {
       // you can do the work you want when the button clicked
    }

结果图片:

此外,您可以参考how to change xamarin frame border thickness案例来设置框架的边框宽度。

vxbzzdmp

vxbzzdmp2#

使用按钮,我也设法解决了这个问题。

<Grid RowDefinitions="*" ColumnDefinitions="*">
        <Button x:Name="ButtonClick" Clicked="OnButtonClicked" Grid.Row="0" Grid.Column="0" Text="My Text" ImageSource="image.png" BorderColor="red" Style="{StaticResource bstyle1}"/>
    </Grid>

参考样式

<Style x:Key="bstyle1" TargetType="Button">

    <Setter Property="MaximumHeightRequest" Value="200"/>
    <Setter Property="MaximumWidthRequest" Value="200"/>
    <Setter Property="Padding" Value="25,5,25,5"/>
    <Setter Property="WidthRequest" Value="200"/>
    <Setter Property="FontSize" Value="15"/>
    <Setter Property="CharacterSpacing" Value="3"/>
    <Setter Property="TextColor" Value="Black"/>
    <Setter Property="CornerRadius" Value="7"/>
    <Setter Property="ContentLayout" Value="Top, 0"/>
    <Setter Property="BackgroundColor" Value="Transparent"/>
    <Setter Property="BorderWidth" Value="3"/>
    <Setter Property="BorderColor" Value="red"/>
    <Setter Property="FontFamily" Value="OpenSansRegular"/>
</Style>
ie3xauqp

ie3xauqp3#

您可以使用DevExpres SimpleButton组件(DevExpress .NET MAUI suite当前免费提供):

<dxc:SimpleButton Padding="0">
   <Image HeightReqiest="24" WidthReqiest="24" />
</dxc:SimpleButton>

相关问题