.NET MAUI工具栏可点击图标按钮添加及问题求助
解决MAUI工具栏图标按钮的两个问题
问题1:图标大小无法修改
直接设置FontImageSource的Size不生效,是因为MAUI的工具栏会根据平台默认布局自动缩放图标,你需要给ToolbarItem本身设置IconHeightRequest和IconWidthRequest属性来控制图标尺寸,而非仅在FontImageSource里设置Size。
问题2:添加点击事件
ToolbarItem本身就支持Clicked事件,直接给带图标的ToolbarItem加上该属性即可,和你第一个带文字的按钮用法完全一致。
修改后的完整XAML代码
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MauiApp1.MainPage"> <ContentPage.ToolbarItems> <ToolbarItem Text="Second Page" Clicked="GotoSecondPage" /> <!-- 修改后的图标ToolbarItem --> <ToolbarItem Clicked="OnIconToolbarClicked" IconHeightRequest="40" IconWidthRequest="40"> <ToolbarItem.IconImageSource> <FontImageSource FontFamily="MaterialIconsOutlined-Regular" Glyph="" Color="Black" Size="40" /> <!-- 这里的Size可与ToolbarItem的尺寸对应 --> </ToolbarItem.IconImageSource> </ToolbarItem> </ContentPage.ToolbarItems> <!-- 以下代码保持不变 --> <Shell.TitleView> <HorizontalStackLayout VerticalOptions="Fill"> <Label Text="Welcome to MAUI" FontFamily="Strande2" TextColor="White" VerticalTextAlignment="Center" VerticalOptions="Center" HeightRequest="50" FontSize="Medium" /> </HorizontalStackLayout> </Shell.TitleView> <ScrollView> <VerticalStackLayout Padding="30,0" Spacing="15"> <Label Text="HOME PAGE" Style="{StaticResource Headline}" SemanticProperties.HeadingLevel="Level1" /> <Image Source="dotnet_bot.png" HeightRequest="130" Aspect="AspectFit" SemanticProperties.Description="dot net bot in a race car number eight" /> <Label Text="Hello, World!" Style="{StaticResource Headline}" SemanticProperties.HeadingLevel="Level1" /> <Button x:Name="CounterBtn" Text="Click me" SemanticProperties.Hint="Counts the number of times you click" Clicked="OnCounterClicked" HorizontalOptions="Fill" /> <Button x:Name="GoToPageTwoButton" Text="Go to Page Two" Clicked="GotoSecondPage" HorizontalOptions="Fill" /> </VerticalStackLayout> </ScrollView> </ContentPage>
额外说明
- 需在后台代码中实现
OnIconToolbarClicked方法,示例:
private void OnIconToolbarClicked(object sender, EventArgs e) { // 写入图标按钮的点击逻辑 }
IconHeightRequest和IconWidthRequest的数值可按需调整,注意不要超过工具栏整体高度,否则图标会被裁剪。不同平台工具栏默认高度有差异,可根据测试结果微调。
内容的提问来源于stack exchange,提问作者Carlos Costa
相关产品推荐
相关产品推荐

