【发布时间】:2021-12-07 13:41:33
【问题描述】:
我的 Mainpage.xaml 文件中有以下 XAML
<StackPanel Visibility="{Binding Path=IsSignedIn, Source={x:Bind Application.Current}}">
<Button Margin="10" Click="OnSignOut">
<StackPanel Orientation="Horizontal">
<SymbolIcon Symbol="Account"/>
<TextBlock Text="Sign Out" Margin="5 0 0 0"/>
</StackPanel>
</Button>
</StackPanel>
如果应用程序的“状态”(在 IsSignedIn 变量中跟踪)已登录,我基本上只想显示退出按钮。
这是调用登录逻辑值“IsSignedIn”的代码
**MainPage.xaml.cs **
private async void OnSignIn(object sender, RoutedEventArgs e)
{
try
{
await(Application.Current as App).SignIn();
}
catch (Exception ex)
{
var messageDialog = new MessageDialog("Authentication Error", ex.Message);
await messageDialog.ShowAsync();
}
}
App.xaml.cs
public async Task SignIn()
{
// First, attempt silent sign in
// If the user's information is already in the app's cache,
// they won't have to sign in again.
try
{
var accounts = await PCA.GetAccountsAsync();
var silentAuthResult = await PCA
.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())
.ExecuteAsync();
Console.WriteLine("User already signed in.");
}
catch (MsalUiRequiredException msalEx)
{
// This exception is thrown when an interactive sign-in is required.
Console.WriteLine("Silent token request failed, user needs to sign-in: " + msalEx.Message);
// Prompt the user to sign-in
var interactiveRequest = PCA.AcquireTokenInteractive(Scopes);
var interactiveAuthResult = await interactiveRequest.ExecuteAsync();
Console.WriteLine($"Successful interactive authentication for: {interactiveAuthResult.Account.Username}");
}
catch (Exception ex)
{
Console.WriteLine("Authentication failed. See exception messsage for more details: " + ex.Message);
}
await GetUserInfo();
IsSignedIn = true;
await InitializeGraphClientAsync();
}
错误信息
绑定路径“Application.Current”无效:在类型“MainPage”上找不到属性“Application”。 MSGraphAPIDemo
对不起,如果这是一个菜鸟问题 - 这是我第一次尝试 XAML / UWP。谢谢。
编辑 1
我创建了一个名为 MainPageViewModel.cs 的新类,如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MSGraphAPIDemo.DataProvider;
using Windows.UI.Xaml;
namespace MSGraphSPAPIDemo.Model
{
public class MainPageViewModel
{
public bool SignedIn = Application.Current.IsSignedIn;
}
}
但我得到的错误是:
CS1061“Application”不包含“IsSignedIn”的定义,并且找不到接受“Application”类型的第一个参数的可访问扩展方法“IsSignedIn”(您是否缺少 using 指令或程序集引用?)
在 App.xaml.cs 中,我有以下代码:
// Is a user signed in?
private bool isSignedIn;
public bool IsSignedIn
{
get { return isSignedIn; }
set
{
isSignedIn = value;
OnPropertyChanged("IsSignedIn");
OnPropertyChanged("IsSignedOut");
}
}
编辑 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MSGraphAPIDemo.DataProvider;
using Windows.UI.Xaml;
namespace MSGraphAPIDemo.Model
{
public class MainPageViewModel
{
public bool SignedIn { get; set; }
public MainPageViewModel()
{
SignedIn = ((App)Application.Current).IsSignedIn;
}
}
}
【问题讨论】: