我正在尝试将 Xamarin.Forms 应用程序更新到 .NET MAUI,目前我正试图通过 Android 的 NavigationPageRenderer 进行移植。在.NET 7中它似乎根本不起作用,说它无法将google.android.material工具栏转换为androidx.appcompat.widget.toolbar。
所以我尝试移植到处理程序。具体来说,是NavigationViewHandler。我可以使用这个获取工具栏信息:
var layout = MainActivity.Activity.FindViewById<LinearLayout>(Resource.Id.navigationlayout_appbar);
Toolbar toolbar = layout.GetChildAt(0);
这可行,但我遇到的问题是我无法设置自定义工具栏。
我在 Platforms/Android/Resources/layout 中有一个 Toolbar.axml 文件,但在 OnCreate 方法中,FindViewById(Resource.Id.toolbar) 返回 null。
在 Xamarin.Forms 中,这样做很容易,因为有 ToolbarResource 属性,该属性将设置为工具栏的布局,并且一切都会正常工作。
如有任何帮助,我们将不胜感激。
谢谢!
我无法更换工具栏,但我找到了修改它的方法。对于任何被困于此的人,这对我有帮助:
public class CustomNavigationPageHandler : NavigationViewHandler
{
protected override void ConnectHandler(View platformView)
{
base.ConnectHandler(platformView);
SetCustomFontTitle(platformView);
}
private void SetCustomFontTitle(View platformView)
{
// This is the toolbar
var toolbar = (Toolbar)MainActivity.Activity.FindViewById<Toolbar>(Resource.Id.navigationlayout_appbar)?.GetChildAt(0);
// Toolbar modifications
}
}
然后,要更改标题视图的外观,您可以像这样获取标题视图:
TextView titleView = null;
for (var i = 0; i < toolbar.ChildCount; i++)
if ((titleView = toolbar.GetChildAt(i) as TextView) != null)
break;
这对我有用,我拥有所有信息,只是没有看到全貌。不是我需要的,但它工作正常
由于框架发生了根本性变化,将 Xamarin.Forms 应用程序移植到 .NET MAUI 可能需要对代码和 UI 组件进行大量修改。由于 .NET MAUI 始终在增长,因此跟上最新的文档和示例至关重要。不过,我可以向您展示如何在 .NET MAUI 中创建自定义工具栏。要将菜单项添加到 .NET MAUI 中的应用程序工具栏,请使用
ToolbarItem
类。以下是如何在 .NET MAUI 应用程序中构建自定义工具栏的简单示例:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="YourNamespace.MainPage">
<ContentPage.ToolbarItems>
<ToolbarItem Text="Custom Item" Clicked="OnCustomItemClicked" />
</ContentPage.ToolbarItems>
<!-- Your content here -->
</ContentPage>
在您的代码隐藏 (
MainPage.xaml.cs
) 中,按如下方式处理自定义项目的点击事件:
private void OnCustomItemClicked(object sender, EventArgs e)
{
// Handle the custom toolbar item click here
}
这会向应用程序工具栏添加一个自定义项目,您可以根据需要设计和调整该项目。但是,如果您需要构建自定义工具栏布局或管理自定义工具栏呈现,.NET MAUI 会提供处理程序。您可以为您的页面构建自定义
Handler
并在 OnMauiToolbarItemPropertyChanged
函数中提供工具栏布局来创建自定义工具栏布局:
public class CustomPageHandler : ContentPageHandler
{
protected override ContentPage CreateNativeView()
{
var nativeView = base.CreateNativeView();
// Set up your custom toolbar layout here
return nativeView;
}
protected override void OnMauiToolbarItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnMauiToolbarItemPropertyChanged(sender, e);
if (e.PropertyName == CustomPage.CustomToolbarItemProperty.PropertyName)
{
// Handle custom toolbar items here
}
}
}
请小心将
CustomPage
更改为您自己页面的名称。请记住将您的自定义处理程序包含在 MainPage.xaml
文件中:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="YourNamespace.MainPage"
Handler="YourNamespace.CustomPageHandler">
<!-- Your content here -->
</ContentPage>