c# - 无法更改 Xamarin Forms v4.1 中的工具栏图标
问题描述
使用 XF Shell 包装应用程序时,工具栏图标在运行时不会更改。示例来源:https ://github.com/chyzy/XF-Shell-ToolbarItem-Issue
如果我使用 new NavigationPage(new MainPage) 而不是 Shell,一切正常(图标更改正确)。
应用程序.xaml.cs:
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new AppShell();
}
}
AppShell.cs
public partial class AppShell : Shell
{
public AppShell ()
{
InitializeComponent ();
this.Items.Add(new ShellSection()
{
Title = "Main Page",
Items =
{
new ShellContent()
{
Content = new MainPage()
}
}
});
}
}
主页.xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:TISample"
x:Class="TISample.MainPage"
Title="Main Page">
<ContentPage.ToolbarItems>
<ToolbarItem x:Name="MyToolbarItem" Clicked="MyToolbarItem_OnClicked"/>
</ContentPage.ToolbarItems>
<StackLayout>
<Label Text="Click the toolbar icon to change its color"
HorizontalOptions="Center"
VerticalOptions="Center" />
</StackLayout>
</ContentPage>
MainPage.xaml.cs
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
_availableIcons = new[] { "red.png", "green.png" };
_currentIcon = _availableIcons.First();
MyToolbarItem.IconImageSource = ImageSource.FromFile(_currentIcon);
}
private string[] _availableIcons;
private string _currentIcon;
private void MyToolbarItem_OnClicked(object sender, EventArgs e)
{
_currentIcon = _availableIcons.First(ai => ai != _currentIcon);
MyToolbarItem.IconImageSource = ImageSource.FromFile(_currentIcon);
}
}
Xamarin Forms Shell 有问题吗?是否可以解决此问题并动态更改图标?
解决方案
我的猜测是,一旦将工具栏项添加到渲染器中的本机控件,更改的属性就不会传播。
您可以使用TitleView
来实现:
<NavigationPage.TitleView>
<StackLayout Orientation="Horizontal">
<Image Source="back_button"
VerticalOptions="CenterAndExpand"
HorizontalOptions="Start" />
<Label Text="Page Title"
HorizontalOptions="StartAndExpand"
VerticalOptions="CenterAndExpand"
FontAttributes="Bold"
FontSize="20"/>
<ImageButton Source="green.png"
VerticalOptions="CenterAndExpand"
HorizontalOptions="End" />
</StackLayout>
</NavigationPage.TitleView>
https://www.andrewhoefling.com/Blog/Post/xamarin-forms-title-view-a-powerful-navigation-view
编辑:要使用 TabbedPage,首先添加 TitleView,然后添加 TabbedPage Children ( https://forums.xamarin.com/discussion/139894/putting-an-image-on-navigation-bar )。
推荐阅读
- reactjs - Nextjs Typescript 图片占位符
- python - Python barplot x轴问题
- sql-server - 我想从日期中提取结束日期(当新日期更新时,新日期第 -1 天是结束日期),但该结束日期的最近日期相同
- android - 警告:找不到包 'system-images;android-30;google_apis_playstore;x86 平台
- css - 没有useBlockLayout的React-Table中的粘性列
- c++ - C ++中优先级队列自定义排序中的异常
- spring - 如何为 google pub sub gRPC 调用配置代理凭据?
- reactjs - 找不到模块:无法解析“/home/manujtiwari/Desktop/portfolio-react/node_modules/react-particles-js/cjs”中的“tsparticles”
- selenium - 如何仅通过指定平台使用 Selenium Grid 运行并行 Appium 测试
- android-studio - 如何避免翻译后的 EditText 被键盘覆盖