无法更改 Xamarin 窗体 v4.1 中的工具栏图标



当应用程序使用 XF Shell 包装时,工具栏图标在运行时不会更改。样本来源:https://github.com/chyzy/XF-Shell-ToolbarItem-Issue

如果我使用新的导航页面(新主页(而不是 Shell,一切正常(图标更改正确(。

App.xaml.cs:

public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new AppShell();
}
}

应用外壳.cs

public partial class AppShell : Shell
{
public AppShell ()
{
InitializeComponent ();
this.Items.Add(new ShellSection()
{
Title = "Main Page",
Items =
{
new ShellContent()
{
Content = new MainPage()
}
}
});
}
}

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>

主页.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

编辑:要使其与选项卡式页面一起使用,请首先添加标题视图,然后添加选项卡式页面子项(https://forums.xamarin.com/discussion/139894/putting-an-image-on-navigation-bar(。

最新更新