如何将字符串值传递给Android渲染页面到PCL页面。
我想将 eventArgs.Account.Properties [“access_token”] 的令牌发送到PCL页面。
我该怎么办?请帮忙。
[assembly: ExportRenderer(typeof(LoginPage), typeof(LoginRender))]
namespace TestApp.Droid.Renderers
{
public class LoginRender : PageRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
{
base.OnElementChanged(e);
// this is a ViewGroup - so should be able to load an AXML file and FindView<>
var activity = this.Context as Activity;
var auth = new OAuth2Authenticator(
clientId: "", // your OAuth2 client id
scope: "user_about_me", // the scopes for the particular API you're accessing, delimited by "+" symbols
authorizeUrl: new Uri("https://www.facebook.com/dialog/oauth"), // the auth URL for the service
redirectUrl: new Uri("https://www.facebook.com/connect/login_success.html")); // the redirect URL for the service
auth.Completed += (sender, eventArgs) => {
if (eventArgs.IsAuthenticated)
{
Toast.MakeText(this.Context, eventArgs.Account.Properties["access_token"], ToastLength.Long).Show();
App.SuccessfulLoginAction.Invoke();
App.SaveToken(eventArgs.Account.Properties["access_token"]);
}
else
{
// The user cancelled
}
};
activity.StartActivity(auth.GetUI(activity));
}
}
}
App.cs
public class App
{
static NavigationPage _NavPage;
public static Page GetMainPage()
{
var profilePage = new ProfilePage();
_NavPage = new NavigationPage(profilePage);
return _NavPage;
}
public static bool IsLoggedIn
{
get { return !string.IsNullOrWhiteSpace(_Token); }
}
static string _Token;
public static string Token
{
get { return _Token; }
}
public static void SaveToken(string token)
{
_Token = token;
}
public static Action SuccessfulLoginAction
{
get
{
return new Action(() => {
_NavPage.Navigation.PopModalAsync();
});
}
}
}
上面是我的App.cs文件代码。静态方法无法返回令牌。
PCL中的ProfilePage.cs
public class ProfilePage : BaseContentPage
{
public ProfilePage()
{
string tk = App.Token;
var lbltoken = new Label()
{
FontSize = 20,
HorizontalOptions = LayoutOptions.CenterAndExpand,
Text = tk,
};
var stack = new StackLayout
{
VerticalOptions = LayoutOptions.StartAndExpand,
Children = { lbltoken },
};
Content = stack;
}
}
答案 0 :(得分:1)
我假设你在这里遵循了这个例子:http://www.benjaminkeen.com/google-maps-coloured-markers/
在这种情况下,您可以通过调用App.Token
如果不起作用,请通过调用App.SaveToken(eventArgs.Account.Properties["access_token"]);
通过编辑,您可以在Label
有值之前设置App.Token
的值。
这里的快速解决方法可能是挂钩Page.Appearing
事件,就像这样;
public class ProfilePage : BaseContentPage
{
private Label _lbltoken;
public ProfilePage()
{
Appearing += (object s, EventArgs a) => {
_lbltoken.Text = App.Token;
};
string tk = App.Token;
_lbltoken = new Label()
{
FontSize = 20,
HorizontalOptions = LayoutOptions.CenterAndExpand,
Text = tk,
};
var stack = new StackLayout
{
VerticalOptions = LayoutOptions.StartAndExpand,
Children = { _lbltoken },
};
Content = stack;
}
}
我已将您的Label
控件设为私有变量,以便我们可以从其他位置轻松引用它,并在ProfilePage
出现时创建一个事件处理程序。
因此,每当您的页面出现时,它都会在App.Token
中设置Label
的值。
这应该有效。但是,您可能最好查看How to login to facebook in Xamarin.Forms等技术。