首页 > 解决方案 > 根据应用身份验证更改母版页项目标签

问题描述

在我的 xamarin 表单应用程序中-当用户未登录时,我希望母版页上的按钮说“登录”。用户登录后,我希望同一个按钮说“注销”。

我使用 INotifyPropertyChanged 创建了一个 masterpageitem 类。我创建了一个 ObservableCollection masterPageItems。我有 listView.ItemsSource = App.masterPageItems;

//masterpageitem.cs

public class MasterPageItem : INotifyPropertyChanged
{
    private string title;
    public string Title
    {
        get
        {
            return title;
        }
        set
        {
            title = value;
            NotifyPropertyChanged("title");
        }
    }

    public string IconSource { get; set; }

    public Type TargetType { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string info)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));
    }
}

//App.xaml.cs

public static ObservableCollection<MasterPageItem> masterPageItems = new ObservableCollection<MasterPageItem>
        {
            new MasterPageItem
            {
                Title = "Home",
                IconSource = "home.png",
                TargetType = typeof(HomePage)
            },
            new MasterPageItem
            {
                Title = "Competitions",
                IconSource = "logo.png",
                TargetType = typeof(Views.PlayerTournaments)
            },
            new MasterPageItem
            {
                Title = App.authenticated?"Sign out":"Sign in",
                IconSource = "logo.png",
                TargetType = typeof(LoginPage)
            }
        };

//Masterpage.xaml.cs

public partial class MasterPage : ContentPage
{
    public ListView ListView { get { return listView; } }


    public MasterPage()
    {
        InitializeComponent();
        listView.ItemsSource = App.masterPageItems;
    }

//Masterpage.xaml

<ListView x:Name="listView">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Grid Padding="5,10">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="30"/>
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
                        <Image Source="{Binding IconSource}" />
                        <Label Grid.Column="1" Text="{Binding Title}" />
                    </Grid>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

//LoginPage.xaml.cs

void UpdateSignInState(UserContext userContext)
    {
        var isSignedIn = userContext.IsLoggedOn;
        btnSignInSignOut.Text = isSignedIn ? "Sign out" : "Sign in";
        App.authenticated = isSignedIn;
        App.masterPageItems[2].Title = App.authenticated ? "Sign out" : "Sign in";
    }

当我注销时 - 当我希望母版页项目说“登录”时,它仍然是“注销”

标签: c#xamarin.forms

解决方案


推荐阅读