首页 > 解决方案 > Xamarin 的动态资源在项目源中不起作用

问题描述

我是 Xamarin 的新手。我尝试了解动态资源,并提出了一个非常简单的项目。我在 App.xaml 中创建了 3 个 String 类型的动态资源,如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<Application
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="MyMobileApp.App">
    <Application.Resources>
        <ResourceDictionary>
            <x:String x:Key="LangAbout">A</x:String>
            <x:String x:Key="LangProfile">P</x:String>
            <x:String x:Key="LangSettings">S</x:String>
        </ResourceDictionary>
    </Application.Resources>
</Application>

这是我的 MenuPageTest.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage Title="Menu"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="MyMobileApp.Views.MenuPageTest">
    <StackLayout VerticalOptions="FillAndExpand">
        <ListView x:Name="ListViewMenu" HasUnevenRows="True">
            <ListView.ItemTemplate><DataTemplate><ViewCell><Grid Padding="10">
                <Label Text="{Binding Text}" FontSize="20"/>
            </Grid></ViewCell></DataTemplate></ListView.ItemTemplate>
            <ListView.ItemsSource><x:Array Type="{x:Type TextCell}">
                <TextCell Text="{DynamicResource LangProfile}"  Detail="0"/>
                <TextCell Text="{DynamicResource LangSettings}" Detail="8"/>
                <TextCell Text="{DynamicResource LangAbout}"    Detail="9"/>
            </x:Array></ListView.ItemsSource>
        </ListView>
        <Button Text="Change Resources" Clicked="Button_Clicked"/>
    </StackLayout>
</ContentPage>

这是我的代码隐藏,MenuPageTest.xaml.cs:

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace MyMobileApp.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MenuPageTest : ContentPage
    {
        public MenuPageTest()
        {
            InitializeComponent();
        }
        private void Button_Clicked(object sender, System.EventArgs e)
        {
            Resources["LangAbout"] = "About";
            Resources["LangProfile"] = "Profile";
            Resources["LangSettings"] = "Settings";
        }
    }
}

当我第一次运行它时,列表正确显示了 3 个项目,“P”、“S”和“A”。当我按下按钮时,我希望这 3 个项目会更新为“个人资料”、“设置”和“关于”,但没有任何改变。

事实上,我进入代码,发现资源确实发生了变化,但变化并没有反映到列表视图中的项目上。任何帮助,将不胜感激。

标签: xamarindynamicresourcesitemssource

解决方案


推荐阅读