Open app from Link Xamarin Forms App links - xamarin

I want to open application from Link, I implemented some steps but didn't work, if anyone have idea about the problem help me, when clicking on this link didn't open application http://amaar-app.com/ar/unit/207
First in android I put this code in MainActivity and SplashActivity
[Activity(Label = "عمار", Icon = "#drawable/icon600",
Theme = "#style/splashscreen", MainLauncher = true, NoHistory = true, Exported = true)]
[IntentFilter(new[] { Android.Content.Intent.ActionView },
DataScheme = "https",
DataHost = "amaar-app.com",
DataPathPrefix = "/ar/unit",
AutoVerify = true,
Categories = new[] { Android.Content.Intent.CategoryDefault, Android.Content.Intent.CategoryBrowsable })]
[IntentFilter(new[] { Android.Content.Intent.ActionView },
DataScheme = "http",
DataHost = "amaar-app.com",
AutoVerify = true,
DataPathPrefix = "/ar/unit",
Categories = new[] { Android.Content.Intent.CategoryDefault, Android.Content.Intent.CategoryBrowsable })]
public class SplashActivity : AppCompatActivity
--
[Activity(Label = "عمار", Icon = "#mipmap/icon", Theme = "#style/MainTheme",
MainLauncher = false,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation,
ScreenOrientation = ScreenOrientation.Portrait,Exported =true)]
[IntentFilter(new[] { Android.Content.Intent.ActionView },
DataScheme = "https",
DataHost = "amaar-app.com",
DataPathPrefix = "/ar/unit",
AutoVerify = true,
Categories = new[] { Android.Content.Intent.CategoryDefault, Android.Content.Intent.CategoryBrowsable })]
[IntentFilter(new[] { Android.Content.Intent.ActionView },
DataScheme = "http",
DataHost = "amaar-app.com",
AutoVerify = true,
DataPathPrefix = "/ar/unit",
Categories = new[] { Android.Content.Intent.CategoryDefault, Android.Content.Intent.CategoryBrowsable })]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
in ios I do that
Enable associated domains
in shared project I do that
protected override void OnAppLinkRequestReceived(Uri uri)
{
Device.BeginInvokeOnMainThread(async () =>
{
await Current.MainPage.DisplayAlert("hi", "hi", "ok");
});
}
in web configuration
https://amaar-app.com/.well-known/apple-app-site-association (for ios)
https://amaar-app.com/.well-known/assetlinks.json (for android)

Related

Error coming string reference not set to an instance of a String. Parameter name: s

I am working on authentication and authorization in JWT. But I have an error coming which do not not why.
builder.Services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(builder.Configuration.GetSection("Jwt:Key").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
I add code like below in appsettings.json :
"JWT": {
"Key": "fc746b61cde4f6665d3f9791446cd5395661860c0075a905ed9810b7391af467",
"Issuer": "Comply",
"Audience": "comply"
}
In Program.cs:
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:Key"]))

Use of DropdownMenu with Jetpack Compose (Material)

I decided to use an OutlinedTextField and DropdownMenu so the user can fill an amount and select a currency.
This looks pretty nice in the preview, but when this code is being run on the device (virtual or physical) the DropdownMenu is being squeezed on the right, and therefore, the dropdown menu isn't actionable anymore.
#Composable
fun Money() {
Row() {
Amount()
Currency()
}
}
#Preview
#Composable
fun Currency() {
var mExpanded by remember { mutableStateOf(false) }
val mCurrencies = listOf("USD", "CHF", "EUR", "MAD") //, "Hyderabad", "Bengaluru", "PUNE")
var mSelectedText by remember { mutableStateOf("") }
var mTextFieldSize by remember { mutableStateOf(Size.Zero) }
val icon = if (mExpanded)
Icons.Filled.KeyboardArrowUp
else
Icons.Filled.KeyboardArrowDown
OutlinedTextField(
value = mSelectedText,
onValueChange = { mSelectedText = it },
modifier = Modifier
.fillMaxWidth()
.onGloballyPositioned { coordinates ->
// This value is used to assign to
// the DropDown the same width
mTextFieldSize = coordinates.size.toSize()
},
label = { Text("Currency") },
trailingIcon = {
Icon(icon, "contentDescription",
Modifier.clickable { mExpanded = !mExpanded })
}
)
DropdownMenu(
expanded = mExpanded,
onDismissRequest = { mExpanded = false },
modifier = Modifier
.width(with(LocalDensity.current) { mTextFieldSize.width.toDp() })
) {
mCurrencies.forEach { label ->
DropdownMenuItem(onClick = {
mSelectedText = label
mExpanded = false
}) {
Text(text = label)
}
}
}
}
#Composable
fun Amount() {
var amount by remember {
mutableStateOf("")
}
OutlinedTextField(
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
value = amount,
onValueChange = { amount = it },
label = { Text(text = "Amount") },
singleLine = true,
trailingIcon = {
if (amount.isNotBlank())
IconButton(onClick = { amount = "" }) {
Icon(
imageVector = Icons.Filled.Clear,
contentDescription = ""
)
}
}
)
}```

Adaptive card column style is working in Adaptive Designer but not in WebChat

I'm using Adaptive Card version 1.2 and I'm trying to add style for Adaptive Column. The style is getting reflected in Adaptive Designer(Web Chat). But the same if I try to check in hosted Web Chat styles are not getting reflected. Also I would like to mention that I'm creating Adaptive card using C#.
But it is looking like this
The i'm using this for webchat (https://cdn.botframework.com/botframework-webchat/latest/webchat.js)
Here is my C# code
AdaptiveCard card = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0));
card.Body.Add(new AdaptiveTextBlock()
{
Text = $"Hello User",
HorizontalAlignment = AdaptiveHorizontalAlignment.Center
});
card.Body.Add(new AdaptiveTextBlock()
{
FontType = AdaptiveFontType.Monospace,
Text = "Would you like to rate us",
Color = AdaptiveTextColor.Good,
Weight = AdaptiveTextWeight.Bolder,
HorizontalAlignment = AdaptiveHorizontalAlignment.Center,
Separator = true
});
card.Body.Add(new AdaptiveColumnSet()
{
Separator = true,
Columns = new List<AdaptiveColumn>()
{
new AdaptiveColumn()
{
Bleed = true,
Width = AdaptiveColumnWidth.Stretch,
Style = AdaptiveContainerStyle.Emphasis,
SelectAction = new AdaptiveSubmitAction()
{
Title = "1",
DataJson = "{ \"Type\": \"1\" }"
},
Items = new List<AdaptiveElement>()
{
new AdaptiveTextBlock()
{
Text = "1",
}
}
},
new AdaptiveColumn()
{
Bleed = true,
Width = AdaptiveColumnWidth.Stretch,
Style = AdaptiveContainerStyle.Accent,
SelectAction = new AdaptiveSubmitAction()
{
Title = "2",
DataJson = "{ \"Type\": \"2\" }"
},
Items = new List<AdaptiveElement>()
{
new AdaptiveTextBlock()
{
Text = $"2"
}
}
},
new AdaptiveColumn()
{
Bleed = true,
Width = AdaptiveColumnWidth.Stretch,
Style = AdaptiveContainerStyle.Good,
SelectAction = new AdaptiveSubmitAction()
{
Title = "3",
DataJson = "{ \"Type\": \"3\" }"
},
Items = new List<AdaptiveElement>()
{
new AdaptiveTextBlock()
{
Text = $"3"
}
}
},
new AdaptiveColumn()
{
Bleed = true,
Width = AdaptiveColumnWidth.Stretch,
Style = AdaptiveContainerStyle.Attention,
SelectAction = new AdaptiveSubmitAction()
{
Title = "4",
DataJson = "{ \"Type\": \"4\" }"
},
Items = new List<AdaptiveElement>()
{
new AdaptiveTextBlock()
{
Text = $"4"
}
}
}
}
});
Please help me on this

Azure AD B2C Authentication dropped when navigating to an MVVM-based page

Two part question: On starting up, My Xamarin.Forms app.cs navigates to a login page (ContentPage) with a button. I click the button and I login successfully with this event handler in the app code behind:
async void OnLoginButtonClicked(object sender, EventArgs e)
{
try
{
bool authenticated = await App.AuthenticationProvider.LoginAsync();
if (authenticated)
{
Application.Current.MainPage = new PapMobLandingPage();
}
else
{
await DisplayAlert("Authentication", "Authentication", "OK");
}
}
catch (MsalException ex)
{
if (ex.ErrorCode == "authentication_canceled")
{
await DisplayAlert("Authentication", "Authentication was cancelled by the user.", "OK");
}
else
{
await DisplayAlert("An error has occurred", "Exception message: " + ex.Message, "OK");
}
}
catch (Exception ex)
{
await DisplayAlert("Authentication", "Authentication failed in a big way. Exception: " + ex.Message, "OK");
}
}
}
I then get redirected to Page 2 (PapMobLandingPage) which also has a button. I click that PapMobLandingPage button and get redirected to a TabbedPage with the details of the logged in user flying right in there from my Azure SQL Database, no problems. All great til now! Here is the event handler:
public async void GoToTabbedPage(object sender, EventArgs args)
{
await Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new BotInTabbedPage());
}
Question 1: There is no OnAppearing() in the BotInTabbedPage (TabbedPage) code behind that checks if the user is logged in... there is no acquiring of tokens going on in the TabbedPage initialization, so how does the app know that I'm logged in on this page??
I looked at a similar question from #Creepin and using the link I could not understand the answer to his original question as to whether you have to authenticate each page individually. Link here:
use of AcquireTokenSilentAsync
The reason I ask question 1 is that the tabbed page above is one of six choices the user gets on sign in, so I needed a dashboard page (MVVM based) with six tiles. When I insert this between Page 2 (PapMobLandingPage) and BotInTabbedPage (TabbedPage), and click on the TabbedPage tile, the tapcommand linked to the tile takes me to the BotInTabbedPage (TabbedPage)... BUT...
NO CLIENT DATA! I HAVE BEEN LOGGED OUT!
So to sum up:
Login Page -> PapMobLandingPage -> BotInTabbedPage = Stays authenticated.
Login Page -> PapMobLandingPage -> Dashboard -> BotInTabbedPage = Drops authentication.
If I use a "vanilla" ContentPage with a button:
Login Page -> PapMobLandingPage -> ContentPage -> BotInTabbedPage = Stays authenticated!
So second question is: does anyone have a clue why?
When I say the Dashboard is MVVM based I mean it has a XAML ContentPage, a .cs code behind, with value bindings to a view model which also has a view model template and a template base. This is the code:
Dashboard XAML:
<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:PapWine;assembly=PapWine"
xmlns:artina="clr-namespace:UXDivers.Artina.Shared;assembly=UXDivers.Artina.Shared"
x:Class="PapWine.DashboardTaskMultipleTilesPage"
BackgroundColor="Black"
Title="{ artina:Translate PageTitleDashboardTaskMultipleTiles }">
<ContentPage.Resources>
<ResourceDictionary>
<artina:BoolMemberTemplateSelector
x:Key="Selector"
MemberName="IsNotification">
<artina:BoolMemberTemplateSelector.TrueDataTemplate>
<DataTemplate>
<local:DashboardAppNotificationItemTemplate
WidthRequest="145"
HeightRequest="145" />
</DataTemplate>
</artina:BoolMemberTemplateSelector.TrueDataTemplate>
<artina:BoolMemberTemplateSelector.FalseDataTemplate>
<DataTemplate>
<local:TaskTilesItemTemplate
ShowBackgroundImage="true"
ShowBackgroundColor="true"
ShowiconColoredCircleBackground="false"
TextColor="{ DynamicResource DashboardIconColor }"
WidthRequest="145"
HeightRequest="145"
/>
</DataTemplate>
</artina:BoolMemberTemplateSelector.FalseDataTemplate>
</artina:BoolMemberTemplateSelector>
</ResourceDictionary>
</ContentPage.Resources>
<ScrollView
Orientation="Both">
<artina:GridOptionsView
WidthRequest="320"
Margin="0"
Padding="10"
ColumnSpacing="10"
RowSpacing="10"
ColumnCount="2"
ItemsSource="{Binding DashboardTaskMultipleTilesList}"
ItemTemplate="{StaticResource Selector}"
/>
</ScrollView>
</ContentPage>
Dashboard XAML.cs
using Microsoft.Identity.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
namespace PapWine
{
public partial class DashboardTaskMultipleTilesPage : ContentPage
{
public DashboardTaskMultipleTilesPage()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, true);
BindingContext = new DashboardTaskMultipleTilesViewModel();
}
protected override async void OnAppearing()
{
base.OnAppearing();
PublicClientApplication PCA = new PublicClientApplication(Constants.ClientID, Constants.Authority);
IEnumerable<IAccount> accounts = await PCA.GetAccountsAsync();
AuthenticationResult authenticationResult = await PCA.AcquireTokenSilentAsync(Constants.Scopes, GetAccountByPolicy(accounts, Constants.PolicySignUpSignIn), Constants.Authority, false);
JObject user = ParseIdToken(authenticationResult.IdToken);
var currentuseroid = user["oid"]?.ToString();
}
private IAccount GetAccountByPolicy(IEnumerable<IAccount> accounts, string policy)
{
foreach (var account in accounts)
{
string userIdentifier = account.HomeAccountId.ObjectId.Split('.')[0];
if (userIdentifier.EndsWith(policy.ToLower())) return account;
}
return null;
}
JObject ParseIdToken(string idToken)
{
// Get the piece with actual user info
idToken = idToken.Split('.')[1];
idToken = Base64UrlDecode(idToken);
return JObject.Parse(idToken);
}
string Base64UrlDecode(string str)
{
str = str.Replace('-', '+').Replace('_', '/');
str = str.PadRight(str.Length + (4 - str.Length % 4) % 4, '=');
var byteArray = Convert.FromBase64String(str);
var decoded = Encoding.UTF8.GetString(byteArray, 0, byteArray.Count());
return decoded;
}
}
}
Dashboard View Model:
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace PapWine
{
public class DashboardTaskMultipleTilesViewModel : ObservableObject
{
private List<DashboardTaskMultipleTileItem> _dashboardTaskMultipleTilesList;
public DashboardTaskMultipleTilesViewModel()
: base(listenCultureChanges: true)
{
LoadData();
}
public List<DashboardTaskMultipleTileItem> DashboardTaskMultipleTilesList
{
get { return _dashboardTaskMultipleTilesList; }
set { SetProperty(ref _dashboardTaskMultipleTilesList, value); }
}
protected override void OnCultureChanged(CultureInfo culture)
{
LoadData();
}
public async Task LogMeOut()
{
bool loggedOut = await App.AuthenticationProvider.LogoutAsync();
if (loggedOut)
{
Application.Current.MainPage = new LandingPagePreLogin();
}
}
private void LoadData()
{
DashboardTaskMultipleTilesList = new List<DashboardTaskMultipleTileItem>
{
//1 line
new DashboardTaskMultipleTileItem
{
Title = "Log Out",
Body = "",
Avatar = "",
BackgroundColor = "transparent",
ShowBackgroundColor = false,
IsNotification = false,
BackgroundImage = "Tiles/DarkBlackTile.jpg",
Icon = FontAwesomeFont.Lock,
IconColour = "White"
},
new DashboardTaskMultipleTileItem
{
Title = "User Settings",
Body = "",
Avatar = "",
BackgroundColor = "transparent",
ShowBackgroundColor = false,
IsNotification = false,
BackgroundImage = "Tiles/DarkBlackTile.jpg",
Icon = FontAwesomeFont.Gear,
IconColour = "White"
},
//2 line
new DashboardTaskMultipleTileItem
{
Title = "User Info",
Body = "",
Avatar = "",
BackgroundColor = "transparent",
ShowBackgroundColor = false,
IsNotification = false,
BackgroundImage = "Tiles/DarkBlackTile.jpg",
Icon = FontAwesomeFont.User,
Badge = 12,
IconColour = "White"
},
new DashboardTaskMultipleTileItem
{
Title = "Papillon Shop",
Body = "",
Avatar = "",
BackgroundColor = "transparent",
ShowBackgroundColor = false,
IsNotification = false,
BackgroundImage = "Tiles/DarkBlackTile.jpg",
Icon = FontAwesomeWeb511Font.store,
Badge = 2,
IconColour = "White"
},
//3 line
new DashboardTaskMultipleTileItem
{
Title = "Check Bottles In",
Body = "",
Avatar = "",
BackgroundColor = "transparent",
ShowBackgroundColor = false,
IsNotification = false,
BackgroundImage = "Tiles/DarkBlackTile.jpg",
Icon = FontAwesomeFont.Book,
IconColour = "White"
},
new DashboardTaskMultipleTileItem
{
Title = "Lay Bottles Down",
Body = "",
Avatar = "",
BackgroundColor = "transparent",
ShowBackgroundColor = false,
IsNotification = false,
BackgroundImage = "Tiles/DarkBlackTile.jpg",
Icon = FontAwesomeFont.Bed,
Badge = 2,
IconColour = "White"
},
};
}
}
public class DashboardTaskMultipleTileItem
{
public string Title { get; set; }
public string Body { get; set; }
public string Avatar { get; set; }
public string BackgroundColor { get; set; }
public string BackgroundImage { get; set; }
public bool ShowBackgroundColor { get; set; }
public bool IsNotification { get; set; }
public string Icon { get; set; }
public int Badge { get; set; }
public string NavigPage { get; set; }
private Xamarin.Forms.Command _tapCommand;
public Xamarin.Forms.Command TapCommand
{
get
{
if (_tapCommand == null)
{
switch (this.Title) {
case "Log Out":
App.AuthenticationProvider.LogoutAsync();
_tapCommand = new Xamarin.Forms.Command(() =>
Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new LogoutSuccessPage()));
break;
case "User Settings":
_tapCommand = new Xamarin.Forms.Command(() =>
Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new UserSettingsPage()));
break;
case "User Info":
_tapCommand = new Xamarin.Forms.Command(() =>
Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new UserProfilePage()));
break;
case "Papillon Shop":
_tapCommand = new Xamarin.Forms.Command(() =>
Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new ProductFamilyMultipleTilesPage()));
break;
case "Check Bottles In":
_tapCommand = new Xamarin.Forms.Command(() =>
Xamarin.Forms.Application.Current.MainPage = new SignBottlesIn());
break;
case "Check Bottles Out":
_tapCommand = new Xamarin.Forms.Command(() =>
Xamarin.Forms.Application.Current.MainPage = new SignBottlesIn());
break;
}
}
return _tapCommand;
}
}
}
}
Tiles Item Template:
using Xamarin.Forms;
namespace PapWine
{
public partial class TaskTilesItemTemplate : TaskTilesItemTemplateBase
{
public TaskTilesItemTemplate()
{
InitializeComponent();
}
private async void OnTileTapped(object sender, ItemTappedEventArgs e)
{
if (e.Item == null)
return;
var content = e.Item as DashboardTaskMultipleTileItem;
//await Navigation.PushAsync(new LayBottlesDown()); //pass content if you want to pass the clicked item object to another page
}
}
}
Tiles Item Template Base:
using System;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace PapWine
{
public class TaskTilesItemTemplateBase : ContentView
{
public uint animationDuration = 250;
public bool _processingTag = false;
public static readonly BindableProperty ShowBackgroundImageProperty =
BindableProperty.Create(
nameof(ShowBackgroundImage),
typeof(bool),
typeof(TaskTilesItemTemplate),
true,
defaultBindingMode: BindingMode.OneWay
);
public bool ShowBackgroundImage
{
get { return (bool)GetValue(ShowBackgroundImageProperty); }
set { SetValue(ShowBackgroundImageProperty, value); }
}
public static readonly BindableProperty ShowBackgroundColorProperty =
BindableProperty.Create (
nameof( ShowBackgroundColor ),
typeof ( bool ),
typeof ( TaskTilesItemTemplate ),
false,
defaultBindingMode : BindingMode.OneWay
);
public bool ShowBackgroundColor {
get { return ( bool )GetValue( ShowBackgroundColorProperty ); }
set { SetValue ( ShowBackgroundColorProperty, value ); }
}
public static readonly BindableProperty ShowiconColoredCircleBackgroundProperty =
BindableProperty.Create (
nameof( ShowiconColoredCircleBackground ),
typeof ( bool ),
typeof (TaskTilesItemTemplate),
true,
defaultBindingMode : BindingMode.OneWay
);
public bool ShowiconColoredCircleBackground {
get { return ( bool )GetValue( ShowiconColoredCircleBackgroundProperty ); }
set { SetValue ( ShowiconColoredCircleBackgroundProperty, value ); }
}
public static readonly BindableProperty TextColorProperty =
BindableProperty.Create (
nameof( TextColor ),
typeof ( Color ),
typeof (TaskTilesItemTemplate),
defaultValue : Color.White,
defaultBindingMode : BindingMode.OneWay
);
public Color TextColor {
get { return ( Color )GetValue( TextColorProperty ); }
set { SetValue ( TextColorProperty, value ); }
}
//added start
public Color IconColour
{
get { return (Color)GetValue(TextColorProperty); }
set { SetValue(TextColorProperty, value); }
}
//added end
public async void OnWidgetTapped(object sender, EventArgs e)
{
if (_processingTag)
{
return;
}
_processingTag = true;
try{
await AnimateItem (this, animationDuration );
await SamplesListFromCategoryPage.NavigateToCategory ((SampleCategory)BindingContext, Navigation);
}finally{
_processingTag = false;
}
}
private async Task AnimateItem(View uiElement, uint duration ){
var originalOpacity = uiElement.Opacity;
await uiElement.FadeTo(.5, duration/2, Easing.CubicIn);
await uiElement.FadeTo(originalOpacity, duration/2, Easing.CubicIn);
}
}
}
LoginAsync looks like this:
public async Task<bool> LoginAsync(bool useSilent = false)
{
bool success = false;
//AuthenticationResult authResult = null;
try
{
AuthenticationResult authenticationResult;
if (useSilent)
{
authenticationResult = await ADB2CClient.AcquireTokenSilentAsync(
Constants.Scopes,
GetAccountByPolicy(await ADB2CClient.GetAccountsAsync(), Constants.PolicySignUpSignIn),
Constants.Authority,
false);
UpdateUserInfo(authenticationResult);
}
else
{
authenticationResult = await ADB2CClient.AcquireTokenAsync(
Constants.Scopes,
GetAccountByPolicy(await ADB2CClient.GetAccountsAsync(), Constants.PolicySignUpSignIn),
App.UiParent);
}
if (User == null)
{
var payload = new JObject();
if (authenticationResult != null && !string.IsNullOrWhiteSpace(authenticationResult.IdToken))
{
payload["access_token"] = authenticationResult.IdToken;
}
User = await TodoItemManager.DefaultManager.CurrentClient.LoginAsync(
MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory,
payload);
success = true;
}
}

How can I access objects from a xaml that I create in cs code?

I'm trying to access some objects that I create with cs (carousel pages with labels, listview and buttons) but I have not had success.
Here reference this by saying that you can work with classId or styleId, but it does not make it very clear how to get the same:
https://developer.xamarin.com/guides/xamarin-forms/xaml/xaml-basics/getting_started_with_xaml/
Here you can see the carousel pages
This is my cs code:
private readonly List<AreaModel> _are = new List<AreaModel>();
public AreasModal()
{
Lista();
}
protected override void OnCurrentPageChanged()
{
base.OnCurrentPageChanged();
var index = Children.IndexOf(CurrentPage);
}
private async void Lista()
{
var listareas = await App.NaturalezaManager.GetAreas();
foreach (var Area in listareas) {
var areas = new AreaModel
{
IdArea = Area.IdArea,
NombreArea = Area.NombreArea
};
_are.Add(areas);
Button boton = new Button
{
Text = "Listo",
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand
};
Children.Add(new ContentPage
{
Content = new StackLayout
{
Children =
{
new StackLayout
{
Orientation = StackOrientation.Horizontal,
Children =
{
new StackLayout
{
Orientation = StackOrientation.Vertical,
Children =
{
new Label
{
Text = Area.NombreArea,
FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)),
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand
}
}
},
new Switch
{
HorizontalOptions = LayoutOptions.EndAndExpand
}
}
},
new ListView
{
ItemsSource = listareas,
ItemTemplate = new DataTemplate(() =>
{
Label nameLabel = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand
};
nameLabel.SetBinding(Label.TextProperty,"NombreArea");
Switch switcher = new Switch
{
HorizontalOptions = LayoutOptions.EndAndExpand
};
return new ViewCell
{
View = new StackLayout
{
Orientation = StackOrientation.Horizontal,
Children =
{
new StackLayout
{
Orientation = StackOrientation.Vertical,
Children =
{
nameLabel
}
},
switcher
}
}
};
})
},
boton
}
}
});
}
}
}
I have to access these objects from the "OnCurrentPageChanged" method but I have no idea how to do it, since if it were xaml code could be obtained with the property x:Name, in advance thanks for the help.

Resources