Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all 79144 articles
Browse latest View live

On Navigation.PushAsync() to Views Page, the ViewModel isn't loading in Xamarin

$
0
0

I have Index Page, which opens up when the App starts. In Index Page there is an Icon called Setting, by clicking it, Settings Page opens up and from there user can Navigate to 'Connections', 'Credentials', 'Proofs' page.

But the problem is that when I navigate to any of these three pages, I can only see the Views and the ViewModel isn't loading e.g. I can see the output of Views Page code but not of the ViewModel.

App.xml.cs

public App()
     {
         InitializeComponent();
     }    

protected override async void OnStart()
    {
        await Host.StartAsync();

        // View models and pages mappings
        var _navigationService = Container.Resolve<INavigationService>();
        _navigationService.AddPageViewModelBinding<MainViewModel, MainPage>();
        _navigationService.AddPageViewModelBinding<ConnectionsViewModel, ConnectionsPage>();
        _navigationService.AddPageViewModelBinding<ConnectionViewModel, ConnectionPage>();
        _navigationService.AddPageViewModelBinding<RegisterViewModel, RegisterPage>();
        _navigationService.AddPageViewModelBinding<AcceptInviteViewModel, AcceptInvitePage>();
        _navigationService.AddPageViewModelBinding<CredentialsViewModel, CredentialsPage>();
        _navigationService.AddPageViewModelBinding<CredentialViewModel, CredentialPage>();
        _navigationService.AddPageViewModelBinding<ProofsViewModel, ProofsPage>();
        _navigationService.AddPageViewModelBinding<ProofViewModel, ProofPage>();
        _navigationService.AddPageViewModelBinding<CreateInvitationViewModel, CreateInvitationPage>();

        if (Preferences.Get(AppConstant.LocalWalletProvisioned, false))
        {
            await _navigationService.NavigateToAsync<MainViewModel>();
        }
        else
        {
            await _navigationService.NavigateToAsync<RegisterViewModel>();
        }

        timer.Enabled = true;
    }

INavigationService.cs

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Osma.Mobile.App.Services.Interfaces
{
    public interface INavigationService
    {
        Task PopModalAsync();

        Task NavigateToAsync(Page page, NavigationType type = NavigationType.Normal);

        Task NavigateToAsync<TViewModel>(object parameter = null, NavigationType type = NavigationType.Normal) where TViewModel : IABaseViewModel;

        Task NavigateToAsync<TViewModel>(TViewModel viewModel, object parameter = null, NavigationType type = NavigationType.Normal) where TViewModel : IABaseViewModel;

        Task AddTabChildToMainView<TViewModel>(TViewModel viewModel, object parameter, int atIndex = -1) where TViewModel : IABaseViewModel;

        Task NavigateBackAsync();

        Task RemoveLastFromBackStackAsync();

        Task NavigateToPopupAsync<TViewModel>(bool animate, TViewModel viewModel) where TViewModel : IABaseViewModel;

        Task NavigateToPopupAsync<TViewModel>(object parameter, bool animate, TViewModel viewModel) where TViewModel : IABaseViewModel;

        Task CloseAllPopupsAsync();

        IList<IABaseViewModel> GetMainViewTabChildren();

        bool RemoveTabChildFromMainView(IABaseViewModel childViewModel);

        void SetCurrentTabOnMainView<TViewModel>();

        Type GetCurrentPageViewModel();

        bool SetCurrentPageTitle(string title);

        void AddPageViewModelBinding<TVm, TP>();

        void AddPopupViewModelBinding<TVm, TV>();
    }
}

If I make the Connections/Credentials/Proof page to be the first page to open up when the App starts, then the ViewModel is loading..

MainPage.xml

<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage     xmlns="http://xamarin.com/schemas/2014/forms"
                xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                xmlns:index="clr-namespace:Osma.Mobile.App.Views.Index;assembly=Osma.Mobile.App"
                xmlns:settings="clr-namespace:Osma.Mobile.App.Views.Settings;assembly=Osma.Mobile.App"
                xmlns:connections="clr-namespace:Osma.Mobile.App.Views.Connections;assembly=Osma.Mobile.App"
                xmlns:credentials="clr-namespace:Osma.Mobile.App.Views.Credentials;assembly=Osma.Mobile.App"
                xmlns:proofs="clr-namespace:Osma.Mobile.App.Views.Proof;assembly=Osma.Mobile.App"
                xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
                x:Class="Osma.Mobile.App.Views.MainPage"
                BackgroundColor="#004B86"
                NavigationPage.HasNavigationBar="False"
                BarBackgroundColor ="#004B86"
                BarTextColor="#004B86"
                SelectedTabColor="#004B86"
                UnselectedTabColor="#004B86"
                Title="Prove"
                CurrentPageChanged="CurrentPageChanged"
                Appearing="Appearing">

    <index:IndexPage
        BindingContext="{Binding Index}">
    </index:IndexPage>

    <settings:SettingsPage
        BindingContext="{Binding Settings}">
    </settings:SettingsPage>

    <connections:ConnectionsPage
        BindingContext="{Binding Connections}">
    </connections:ConnectionsPage>

    <credentials:CredentialsPage
        BindingContext="{Binding Credentials}">
    </credentials:CredentialsPage>

    <proofs:ProofsPage
        BindingContext="{Binding Proof}">
    </proofs:ProofsPage>

</TabbedPage>

MainPage.xml.cs

using Osma.Mobile.App.ViewModels;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Osma.Mobile.App.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MainPage : TabbedPage, IRootView
    {
        public MainPage ()
        {
            InitializeComponent ();
        }

        private new void CurrentPageChanged(object sender, System.EventArgs e) => Title = GetPageName(CurrentPage);

        private new void Appearing(object sender, System.EventArgs e) => Title = GetPageName(CurrentPage);

        private string GetPageName(Page page)
        {
            if (page.BindingContext is ABaseViewModel vmBase)
                return vmBase.Name;
            return null;
        }
    }
}

MainViewModel.cs

using System.Threading.Tasks;
using Acr.UserDialogs;
using Osma.Mobile.App.Services.Interfaces;
using Osma.Mobile.App.ViewModels.Connections;
using Osma.Mobile.App.ViewModels.CreateInvitation;
using Osma.Mobile.App.ViewModels.Credentials;
using Osma.Mobile.App.ViewModels.Proof;
using ReactiveUI;

namespace Osma.Mobile.App.ViewModels
{
    public class MainViewModel : ABaseViewModel
    {
        public MainViewModel(
            IUserDialogs userDialogs,
            INavigationService navigationService,
            ConnectionsViewModel connectionsViewModel,
            CredentialsViewModel credentialsViewModel,
            ProofsViewModel proofsViewModel,
            CreateInvitationViewModel createInvitationViewModel
        ) : base(
                nameof(MainViewModel),
                userDialogs,
                navigationService
        )
        {
            Connections = connectionsViewModel;
            Credentials = credentialsViewModel;
            Proof = proofsViewModel;
            CreateInvitation = createInvitationViewModel;
        }

        public override async Task InitializeAsync(object navigationData)
        {
            await Connections.InitializeAsync(null);
            await Credentials.InitializeAsync(null);
            await Proof.InitializeAsync(null);
            await CreateInvitation.InitializeAsync(null);
            await base.InitializeAsync(navigationData);
        }

        #region Bindable Properties

        private ConnectionsViewModel _connections;
        public ConnectionsViewModel Connections
        {
            get => _connections;
            set => this.RaiseAndSetIfChanged(ref _connections, value);
        }

        private CredentialsViewModel _credentials;
        public CredentialsViewModel Credentials
        {
            get => _credentials;
            set => this.RaiseAndSetIfChanged(ref _credentials, value);
        }

        private ProofsViewModel _proof;
        public ProofsViewModel Proof
        {
            get => _proof;
            set => this.RaiseAndSetIfChanged(ref _proof, value);
        }

        private CreateInvitationViewModel _createInvitation;
        public CreateInvitationViewModel CreateInvitation
        {
            get => _createInvitation;
            set => this.RaiseAndSetIfChanged(ref _createInvitation, value);
        }
        #endregion
    }
}

ConnectionsViewModel.cs

using Osma.Mobile.App.Events;
using Osma.Mobile.App.Extensions;
using Osma.Mobile.App.Services;
using Osma.Mobile.App.Services.Interfaces;
using Osma.Mobile.App.Utilities;
using Osma.Mobile.App.ViewModels.CreateInvitation;
...
...

namespace Osma.Mobile.App.ViewModels.Connections
{
    public class ConnectionsViewModel : ABaseViewModel
    {
        private readonly IConnectionService _connectionService;
        private readonly IMessageService _messageService;
        private readonly IAgentProvider _agentContextProvider;
        private readonly IEventAggregator _eventAggregator;
        private readonly ILifetimeScope _scope;

        public ConnectionsViewModel(IUserDialogs userDialogs,
                                    INavigationService navigationService,
                                    IConnectionService connectionService,
                                    IMessageService messageService,
                                    IAgentProvider agentContextProvider,
                                    IEventAggregator eventAggregator,
                                    ILifetimeScope scope) :
                                    base("Connections", userDialogs, navigationService)
        {
            _connectionService = connectionService;
            _messageService = messageService;
            _agentContextProvider = agentContextProvider;
            _eventAggregator = eventAggregator;
            _scope = scope;
        }

        public override async Task InitializeAsync(object navigationData)
        {
            await RefreshConnections();

            _eventAggregator.GetEventByType<ApplicationEvent>()
                            .Where(_ => _.Type == ApplicationEventType.ConnectionsUpdated)
                            .Subscribe(async _ => await RefreshConnections());

            await base.InitializeAsync(navigationData);
        }
        .....
    .....
    }
}

ConnectionsPage.xml

<?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:components="clr-namespace:Osma.Mobile.App.Views.Components;assembly=Osma.Mobile.App"
             xmlns:converters="clr-namespace:Osma.Mobile.App.Converters;assembly=Osma.Mobile.App"
             xmlns:behaviours="clr-namespace:Osma.Mobile.App.Behaviors;assembly=Osma.Mobile.App"
             x:Class="Osma.Mobile.App.Views.Connections.ConnectionsPage"
             Title="Connections">

    <ContentPage.Resources>
        <ResourceDictionary>
            <converters:SelecteditemEventArgsToSelectedItemConverter x:Key="SelectedItemConverter" />
            <converters:InverseBooleanConverter x:Key="BooleanInverse" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <!--
    <ContentPage.ToolbarItems>
        <ToolbarItem Name="Add Connection" Order="Primary" Text="Connect" Priority="0" Command ="{Binding ScanInviteCommand}"/>
        <ToolbarItem Name="CreateInvitation" Order="Secondary" Text="Create Invitation" ios:NavigationPage.PrefersLargeTitles="true" Priority="0" Command ="{Binding CreateInvitationCommand}"/>
    </ContentPage.ToolbarItems>
    -->
    <ContentPage.Content>
        <StackLayout>
            <StackLayout
                IsVisible="{Binding HasConnections}">
                <ListView
                    ...
                    ...
                    ...

                </ListView>
            </StackLayout>
            <StackLayout
                VerticalOptions="FillAndExpand"
                IsVisible="{Binding HasConnections, Converter={StaticResource BooleanInverse}}">
                <StackLayout
                    Orientation="Vertical"
                    VerticalOptions="CenterAndExpand"
                    HorizontalOptions="CenterAndExpand">
                    <ActivityIndicator
                        IsVisible="{Binding RefreshingConnections}"
                        IsRunning="{Binding RefreshingConnections}"/>
                    <Label
                        HorizontalOptions="CenterAndExpand"
                        HorizontalTextAlignment="Center"
                        IsVisible="{Binding RefreshingConnections, Converter={StaticResource BooleanInverse}}" 
                        Text="You have no connections - Click connect to get started"
                        TextColor="White"/>
                </StackLayout>
            </StackLayout>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

SettingsPage.xml

<?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:forms="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
    xmlns:views="clr-namespace:Osma.Mobile.App.Views.Settings;assembly=Osma.Mobile.App"
    xmlns:converters="clr-namespace:Osma.Mobile.App.Converters;assembly=Osma.Mobile.App"
    x:Class="Osma.Mobile.App.Views.Settings.SettingsPage"
    NavigationPage.HasNavigationBar="False"
    BackgroundColor="#004B86">

    <ContentPage.Content>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="70" />
                <RowDefinition Height="50" />
            </Grid.RowDefinitions>
            <Grid Grid.Row="0">
                <ImageButton
                    Source="drawable/BackArrow.png"
                    WidthRequest = "30"
                    HeightRequest = "30"
                    MinimumHeightRequest = "15"
                    MinimumWidthRequest = "15"
                    BackgroundColor="#004B86" VerticalOptions="Start" HorizontalOptions="Start" Padding="0" Margin="10,10,0,0"
                    Clicked="IndexPage" />
                <Label
                    FontSize="20"
                    HorizontalOptions="Start"
                    Text="Settings"
                    TextColor="White" VerticalOptions="Start" Margin="60,10,0,0">
                    <Label.GestureRecognizers>
                        <TapGestureRecognizer Command="{Binding IndexPageCommand}" />
                    </Label.GestureRecognizers>
                </Label>
            </Grid>

            <Grid Grid.Row="1">
                <BoxView Color="#004B79"
                 />
                <ImageButton
                    Source="drawable/connection_icon.png"
                    WidthRequest = "30"
                    HeightRequest = "30"
                    MinimumHeightRequest = "15"
                    MinimumWidthRequest = "15"
                    BackgroundColor="#004B86" VerticalOptions="Start" HorizontalOptions="Start" Padding="0" Margin="10,10,0,0"
                    Clicked="ConnectionsPage"
                    />
                <Label
                    FontSize="20"
                    HorizontalOptions="Start"
                    Text="Connections"
                    TextColor="White" VerticalOptions="Start" Margin="60,10,0,0">
                    <Label.GestureRecognizers>
                        <TapGestureRecognizer Command="{Binding ConnectionsPageCommand}" />
                    </Label.GestureRecognizers>
                </Label>
            </Grid>

        </Grid>
    </ContentPage.Content>
</ContentPage>

SettingsPage.xml.cs

using System;
using System.Windows.Input;
using System.Threading.Tasks;
using Xamarin.Forms;
using Osma.Mobile.App.Views.Index;
using Osma.Mobile.App.Views.Connections;

namespace Osma.Mobile.App.Views.Settings
{
    public partial class SettingsPage : ContentPage
    {
        public SettingsPage()
        {
            InitializeComponent();
            BindingContext = this;
        }

        public async Task IndexPageNavigate()
        {
            await Navigation.PushAsync(new IndexPage());
        }
        public async Task ConnectionsPageNavigate()
        {
            await Navigation.PushAsync(new ConnectionsPage());
        }

        #region Bindable Command
        public ICommand IndexPageCommand => new Command(async () => await IndexPageNavigate());
        public ICommand ConnectionsPageCommand => new Command(async () => await ConnectionsPageNavigate());
        #endregion

        private async void IndexPage(object sender, System.EventArgs e) {  
            await Navigation.PushAsync(new IndexPage());  
        }
        private async void ConnectionsPage(object sender, System.EventArgs e)
        {
            await Navigation.PushAsync(new ConnectionsPage());
        }
    }
}

HttpClient Sending X509 Certificate

$
0
0

Hey Everyone,

I am working on a Xamarin Forms project that needs to send out a Http request that includes a certificate for authentication.

I have the code working to get the certificate, which is a PFX, and pass it to my HttpClient but when I make the request I always get back a 403 error. The code below is how I am sending the message:

// Attach certifcate collection to handler.
 var handler = new HttpClientHandler();
 handler.ClientCertificateOptions = ClientCertificateOption.Manual;
 handler.ClientCertificates.AddRange(GetCertificate());

 // Construct client with handler.
var client = new HttpClient(handler);

// Make request.
var result = client.GetAsync("urlgoeshere").GetAwaiter().GetResult();
var responsebody = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();

I removed the real URL, but with the correct one it is always a 403 error.

I then tested this with a HttpWebRequest and I get through just fine, the code for that is as follows:

X509Certificate2Collection certificate = GetCertificate();
var httpRequest = (HttpWebRequest)WebRequest.Create("urlgoeshere");
httpRequest.ClientCertificates = certificate;
HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse();

So I am curious if anyone has seen this before and if they have what the difference is? And how you could get this fixed to work with the HttpClient?

Can't debug my app at iOS simulators. ( Going back to home screen while starting )

$
0
0

My app on iOS simulator turning back to main screen after launchscreen. Here is a video that explains : https://streamable.com/rufqie

  • This issue doesn't show up at iPhone 11 iOS 13.6, but other simulators have same.
  • i can click on simulator and manually open app. it continuous but it doesn't hit the breakpoints also.
  • I tried another app simulators works fine so the problem is in my solution.
    Where should i suspect ?

Is it possible to replace a colour inside an Image object?

$
0
0

Hi All,

I am currently working on a speech generation device for children using Xamarin.Forms, and I was trying to create the ability for the pictograms that depict people to have the skin tone change dynamically based upon which one is set in the application's settings. I have created non-aliased drawable resources that contain sections that are set to chromakey green, like such:

Ideally, I would like to be able to read said image, replace any chromakey green pixels with the relevant skin tone colour, then return that object to the caller. I have seen some references online to converting the image to a bitmap, then going through each pixel to replace with the correct colour, but I am struggling to find anything that might work cross platform on Android, iOS and UWP.

Has anyone done anything like this? I could create a new image pictogram for each skin tone, but that will blow out the number of pictograms by about 8 times, which will make it difficult for the user to browse (the end application is going to have some four or five hundred pictograms)

Regards
Ryan Abrahams

Prism, binding properties and C# 8

$
0
0

I just started a new Xamarin.Forms project with Prism to test out some C# 8 features, first and foremost what it's like to work with nullable reference types enabled. I've come at an issue that I'm not sure what the best way to resolve it is. When declaring binding properties in my ViewModel, I use the following code:

private string _userName;
public string UserName
{
    get { return _userName; }
    set { SetProperty(ref _userName, value); }
}

The problem is that VS will show a warning saying "Non-nullable field '_userName' is uninitialized. Consider declaring the field as nullable." I considered the following solutions, but I'm not sure what the best one is:

  • Declaring the field nullable. But that would negate the whole thing of woring with nullable reference types.
  • Using code tags to suppress the warning for only the fields and not the properties
  • Assigning some default value (string.Empty) to the field. This seems fine for a simple string, but complications arise when using other types. When I have a Command, for example, I would have to initialize the field with a default empty Command just to then initialize the actual property with the command I actually want in the VM constructor. I would get this:
private ICommand _someCommand = new Command();
public ICommand SomeCommand
{
    get { return _someCommand; }
    set { SetProperty(ref _someCommand, value); }
}

// In the ctor:

SomeCommand = new Command(SomeMethod);

So I'm no seeing an ideal solution here. Can anybody help?

When and why do I need to create bindable properties

$
0
0

Hi all,
I don't quite understand when I need to create a bindable property to use data binding and when I don't.

When I use a ListView, set it's source to an ObservableCollection I will be able to create a ViewCell in XAML that contains a Label and bind a property of the PricePeriod Class to the Text property of the label like so and that works fine.

However, when I create a new ContentPage, create a field e.g public bool ViewIsVisible {get; set;}, set the BindingContext of the page in the constructor like so: BindingContext = this; and try to bind to that in XAML <ActivityIndicator IsVisible="{Binding ViewIsVisible}" it does not work and I need to create a bindable property.

I know how to create bindable properties, so that's not a problem, but I would really appreciate if somebody could tell me why I don't need a bindable property in the ListView, but need one on my ContentPage.

Binding to list causing race conditions

$
0
0

I have an ICollectionChanged list bound to a ListView.
This list changes based on external factors, and the Listview responds to changes by refreshing its content.

However, from time to time I get an exception where the Listview apparently is enumerating the content of the list, while the list content is changing, for example when the list is cleared while the ListView is enumerating the list.

What is a good pattern for eliminating this race condition?

One approach is to not update the list, but rather replace the binding with a new copy of the list when content changes. That is however not ideal, as the ListView listens to CollectionChanged events such as Add and Remove and handles those events in an elegant way. Replacing the binding at any change will cause the entire ListView to be refreshed for any collection change.

Another approach would be to somehow gate CollectionChanged notifications to let the ListView complete its enumeration before getting the next update event. Not sure how to do that though.

Yet another possible approach is to introduce a delay between CollectionChanged notifications, to let the ListView catch up. I think I like that approach.

Stick StackLayout at the bottom of the page

$
0
0

Hi,

I am new to Xamarin.forms and I am trying to create a view like Yahoo Weather App(Image in the background and first stacklayout to start from bottom of the page). I want the first stacklayout to start at the bottom of the page and the other contents below that, so the user can scroll up to see the content below the first stacklayout. So far, I have tried the adjusting the height by setting the height property in the OnAppearing() and it works when I redirect the page from some other page but doesn't work when the App is first loaded.

HomePage.xaml

<ContentPage.ToolbarItems>
    <ToolbarItem Text="Option1"></ToolbarItem>
        <ToolbarItem Text="Option2"></ToolbarItem>

    </ContentPage.ToolbarItems>
    <!--<NavigationPage.Icon>
        <OnPlatform x:TypeArguments="FileImageSource">
            <On Platform="iOS" Value="tab_feed.png"/>
        </OnPlatform>
    </NavigationPage.Icon>-->

<ContentPage.Content>
<StackLayout Orientation="Horizontal" >

        <ScrollView>
                <StackLayout Orientation="Vertical" VerticalOptions="EndAndExpand">
                    <Frame BorderColor="Gray" CornerRadius="5" Padding="5" Margin="10" VerticalOptions="EndAndExpand">
                        <Grid VerticalOptions="EndAndExpand">
                            <Grid.RowDefinitions>
                                <RowDefinition></RowDefinition>
                                <RowDefinition Height="2"></RowDefinition>
                                <RowDefinition></RowDefinition>
                                <RowDefinition></RowDefinition>
                                <RowDefinition></RowDefinition>
                                <RowDefinition></RowDefinition>
                                <RowDefinition Height="*"></RowDefinition>
                                <RowDefinition></RowDefinition>
                                <RowDefinition></RowDefinition>
                                <RowDefinition></RowDefinition>
                            </Grid.RowDefinitions>

                            <Label x:Name="Label1" FontSize="Large" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="4" ></Label>
                            <Label x:Name="Label2"  FontSize="Medium" Grid.Row="0" Grid.Column="3" Grid.ColumnSpan="2"></Label>
                            <BoxView BackgroundColor="Black" Grid.Row="1" Grid.ColumnSpan="6"></BoxView>

                            <Label x:Name="Label3" FontSize="Large" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Grid.RowSpan="3"></Label>
                            <Label Text="Label4" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Grid.RowSpan="3"></Label>
                            <Label x:Name="Label5" Grid.Row="5" Grid.ColumnSpan="2"></Label>
                            <Label x:Name="Label6" Grid.Row="2" Grid.Column="3" Grid.ColumnSpan="2"></Label>
                            <Label x:Name="Label7" Grid.Row="3" Grid.Column="3" Grid.ColumnSpan="2"></Label>
                            <Label x:Name="Label8" Grid.Row="4" Grid.Column="3" Grid.ColumnSpan="2"></Label>
                            <Label x:Name="Label9" Grid.Row="5" Grid.Column="3" Grid.ColumnSpan="2"></Label>

                            <CollectionView x:Name="collecview1" WidthRequest="100"  Grid.Row="6" Grid.RowSpan="3" Grid.ColumnSpan="6" ItemsLayout="HorizontalList" >
                                <CollectionView.ItemTemplate>
                                    <DataTemplate>
                                        <StackLayout Orientation="Vertical" Padding="5,25,30,25" VerticalOptions="Center">
                                            <Label Text="{Binding Text}"></Label>
                                            <Image Source="{Binding Text}"></Image>
                                            <Label Text="{Binding Text}" HorizontalTextAlignment="Center"></Label>
                                        </StackLayout>
                                    </DataTemplate>
                                </CollectionView.ItemTemplate>
                            </CollectionView>

                        </Grid>
                    </Frame>
                    <Frame BorderColor="Gray" CornerRadius="5" Padding="5" Margin="10">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*"></RowDefinition>

                            </Grid.RowDefinitions>

                            <StackLayout Grid.Row="0" Grid.Column="0">
                                <Label Text="Label10"></Label>
                                <BoxView BackgroundColor="Gray" HeightRequest="2"></BoxView>
                                <CollectionView x:Name="collecview2" ItemsLayout="VerticalList" ItemSizingStrategy="MeasureAllItems">
                                    <CollectionView.ItemTemplate>
                                        <DataTemplate>
                                            <Grid>
                                                <Grid.RowDefinitions>
                                                    <RowDefinition Height="30" />
                                                </Grid.RowDefinitions>
                                                <Grid.ColumnDefinitions>
                                                    <ColumnDefinition Width="*"  />
                                                    <ColumnDefinition Width="Auto" />
                                                    <ColumnDefinition Width="Auto" />
                                                    <ColumnDefinition Width="Auto" />
                                                    <ColumnDefinition Width="*" />
                                                </Grid.ColumnDefinitions>

                                                <Label Text="{Binding Text}" Grid.Column="0" HorizontalTextAlignment="End" ></Label>
                                                <Label Text="Image" Grid.Column="1"></Label>
                                                <!--<Image Source="{Binding IconSource}" Grid.Column="1"></Image>-->
                                                <Label Text="{Binding Text}" FontAttributes="Bold" Grid.Column="2"></Label>
                                                <Label Text="{Binding Text}" Grid.Column="3"></Label>
                                                <Label Text="{Binding Text}" Grid.Column="4"></Label>

                                            </Grid>
                                        </DataTemplate>
                                    </CollectionView.ItemTemplate>

                                </CollectionView>
                            </StackLayout>
                        </Grid>
                    </Frame>

                    <Frame BorderColor="Gray" CornerRadius="5" Padding="5" Margin="10">
                        <StackLayout>
                            <Label Text="Label23"></Label>
                            <BoxView BackgroundColor="Black" HeightRequest="2"></BoxView>
                        </StackLayout>
                    </Frame>
                </StackLayout>
            </ScrollView>

    </StackLayout>
</ContentPage.Content>

MainPage.xaml.cs

[DesignTimeVisible(false)]
public partial class MainPage : MasterDetailPage
{
public MainPage()
{
InitializeComponent();

        MasterBehavior = MasterBehavior.Split;
    }   

    public MainPage(string City, string lockey,string StateID)
    {
        InitializeComponent();    
    }


}     

HomePage.xaml.cs

protected override void OnAppearing()
{
base.OnAppearing();
firstStacklayout.Margin = new Thickness(0, Application.Current.MainPage.Height*0.5, 0, 0);
}

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>

<MasterDetailPage.Master>


    <local:MenuPage Title="MenuPage" x:Name="menuPage"></local:MenuPage>


</MasterDetailPage.Master>

<MasterDetailPage.Detail>
    <local:HomePage Title="HomePage" x:Name="homePage" BackgroundImageSource="raleigh.jpg"></local:HomePage>
</MasterDetailPage.Detail>

Can anyone help me with this please?


How to access data from sensors

$
0
0

Hi,

We wrote an app for a device that reads CO2 data from a sensor. The device can plug into a desktop or a laptop and then read the data from the sensor via a serial port.

But now, we want to convert this app to plug into a smartphone instead of a laptop/pc. My question is, how will the smartphone read off data from the sensor? Is there a "serial port" in smartphones? I would like to eventually have the device send data via wi-fi or Bluetooth . But for now, it's using USB cable.

This maybe a dumb question. Appreciate any insight from anyone who has experience developing apps for smartphones.

Firebase dependency service

$
0
0

Hello guys, I need your help with something

I am using firebase with dependency service.

I am already login the user, signing the user and inserting a new User into Firestore

The thing is That I cant seemed to update the User, everytime I update the User, it tells me the ID of the document is null, witch I do not get becouse I get the id when I read the document from the collection

 List<User> users;

        public UserProfileDroid() {
            users = new List<User>();
        }

        bool hasRead = false;
        public Task<bool> DeleteUser(User user) {
            throw new NotImplementedException();
        }

        public bool InsertUser(User user) {
            try {
                var collection = FirebaseFirestore.Instance.Collection("Users");
                var UserDocument = new Dictionary<string, Java.Lang.Object> {
                { "ID", FirebaseAuth.Instance.CurrentUser.Uid },
                { "imageUrl", user.ImageUrl },
                { "Tipo", user.Tipo },
                { "Nombre", $"{user.Nombre} {user.SegundoNombre} {user.Apellido}" },
                { "Email", user.CorreoElectronico },
                { "Telefono Local", user.TelefonoLocal },
                { "Telefono Celular", user.TelefonoCelular },
                { "Cedula", user.Cedula },
                { "Fecha de nacimiento", user.FechaNacimiento },
                { "Genero", user.Genero},
                { "Pais", user.Pais },
                { "Estado", user.Estado },
                { "Capital", user.Capital },
                { "Ciudad", user.Ciudad },
                { "Direccion Principal", user.DireccionPrincipal },
                { "Direccion 1", user.Direccion1 },
                { "Direccion 2", user.Direccion2 },
                { "Direccion 3", user.Direccion3 },
                { "Direccion 4", user.Direccion4 },
                { "Algo Interesante", user.AlgoInteresante },
                { "Habilidades", user.Habilidades}
            };

                collection.Add(UserDocument);

                return true;

            } catch (Exception e) {

                App.Current.MainPage.DisplayAlert("Error", e.Message, "ok");
                return false;
            }
        }

        public void OnComplete(Android.Gms.Tasks.Task task) {
            if (task.IsSuccessful) {
                QuerySnapshot document = (QuerySnapshot)task.Result;
                users.Clear();
                foreach (var doc in document.Documents) {

                    User user = new User();

                    user.Id = doc.Id;
                    user.ImageUrl = doc.Get("imageUrl").ToString();
                    user.Tipo = doc.Get("Tipo").ToString();
                    user.Nombre = doc.Get("Nombre").ToString();
                    user.CorreoElectronico = doc.Get("Email").ToString();
                    user.TelefonoLocal = doc.Get("Telefono Local").ToString();
                    user.TelefonoCelular = doc.Get("Telefono Celular").ToString();
                    user.Cedula = doc.Get("Cedula").ToString();
                    user.FechaNacimiento = doc.Get("Fecha de nacimiento").ToString();
                    user.Genero = doc.Get("Genero").ToString();
                    user.Pais = doc.Get("Pais").ToString();
                    user.Estado = doc.Get("Estado").ToString();
                    user.Ciudad = doc.Get("Ciudad").ToString();
                    user.DireccionPrincipal = doc.Get("Direccion Principal").ToString();
                    user.Direccion1 = doc.Get("Direccion 1").ToString();
                    user.Direccion2 = doc.Get("Direccion 2").ToString();
                    user.Direccion3 = doc.Get("Direccion 3").ToString();
                    user.Direccion4 = doc.Get("Direccion 4").ToString();
                    user.AlgoInteresante = doc.Get("Algo Interesante").ToString();
                    user.Habilidades = doc.Get("Habilidades").ToString();

                    users.Add(user);
                }
            } else {
                users.Clear();
            }

            hasRead = true;
        }

        public async Task<IList<User>> ReadUser() {
            var collection = FirebaseFirestore.Instance.Collection("Users");
            collection.Get().AddOnCompleteListener(this);

            for (int i = 0; i < 25; i++) {
                await System.Threading.Tasks.Task.Delay(100);
                if (hasRead) {
                    break;
                }
            }

            return users;
        }

        public async Task<bool> UpdateUser(User user) {
            try {
                var collection = FirebaseFirestore.Instance.Collection("Users");
                collection.Document(user.Id).Update(
                    "imageUrl", user.ImageUrl,
                    "Tipo", user.Tipo,
                    "Nombre", user.Nombre,
                    "Telefono Local", user.TelefonoLocal,
                    "Telefono Celular", user.TelefonoCelular,
                    "Cedula", user.Cedula,
                    "Fecha de nacimiento", user.FechaNacimiento,
                    "Genero", user.Genero,
                    "Pais", user.Pais,
                    "Estado", user.Estado,
                    "Ciudad", user.Ciudad,
                    "Capital", user.Capital,
                    "Direccion Principal", user.DireccionPrincipal,
                    "Direccion 1", user.Direccion1,
                    "Direccion 2", user.Direccion2,
                    "Direccion 3", user.Direccion3,
                    "Direccion 4", user.Direccion4); 

                return true;
            } catch (Exception e) {

                await App.Current.MainPage.DisplayAlert("error", e.Message, "ok");
                return false;   
            }
        }

this is my Interface

  bool InsertUser(User user);
        Task<bool> DeleteUser(User user);
        Task<bool> UpdateUser(User user);
        Task<IList<User>> ReadUser();

and here is where I update my user

 private async void SeveBton_Clicked(object sender, EventArgs e) {

            User user = new User();

            Debug.WriteLine("tis is my ID: " + user.Id);

            user.Nombre = NombreEntry.Text;
            user.Tipo = TipoUsuarioPicker.SelectedItem.ToString();
             user.SegundoNombre = SegundoNombreEntry.Text;
             user.Apellido = ApellidoEntry.Text;
             user.FechaNacimiento = FechaNacientoEntry.Text;
             user.Genero = GeneroPicker.SelectedItem.ToString();
             user.Cedula = $"{CedulaPrefijo.SelectedItem}-{IdEntry.Text}";
             user.TelefonoCelular = $"{PrefijoTelefonoPicker.SelectedItem}-{CelularEntry}";
             user.TelefonoLocal = TelefonoLocalEntry.Text;
             user.Pais = PaisPicker.SelectedItem.ToString();
             user.Ciudad = CiudadesPicker.SelectedItem.ToString(); 
             user.Estado = EstadoPicker.SelectedItem.ToString();
            user.Capital = CapitalPicker.SelectedItem.ToString();
             user.DireccionPrincipal = DireccionPrincipalEntry.Text;
             user.Direccion1 = DireccionOpciona1Entry.Text;
             user.Direccion2 = DireccionOpciona2Entry.Text;
             user.Direccion3 = DireccionOpciona3Entry.Text;
             user.Direccion4 = DireccionOpciona4Entry.Text;
             user.AlgoInteresante = BioEntry.Text;
             user.Habilidades = HabilidadesPicker.SelectedItem.ToString();

            user.ImageUrl = await StoreImages(mediaFile.GetStream(), "UserImage", Path.GetExtension(mediaFile.Path));


            await userProfile.UpdateUser(user);
            await Navigation.PopAsync();

        }

async\await - How to get the timing correct?

$
0
0

In my Xamarin Forms App, because the App will write to the Android Storage, at the beginning of the App, I check for storage write Permissions...

  public MainPage()
        {
            InitializeComponent();

            StoragePermissionsWriteCheck().Wait();
            if (!MyGlobals.CanWriteToStorage)
            {
                StoragePermissionsMsg();
                return;
            }
---
       public async void StoragePermissionsWriteCheck()
        {
            try
            {
                var permissions = await Xamarin.Essentials.Permissions.CheckStatusAsync<Permissions.StorageWrite>();
                if (permissions != PermissionStatus.Granted)
                {
                    permissions = await Permissions.RequestAsync<Xamarin.Essentials.Permissions.StorageWrite>();
                    if (permissions == PermissionStatus.Granted)
                    {
                        MyGlobals.CanWriteToStorage = true;
                    }
                    else
                    {
                        MyGlobals.CanWriteToStorage = false;
                    }
                }
                else
                {
                    MyGlobals.CanWriteToStorage = true;
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Check Permissions error.", ex.ToString(), "OK");
            }
        }
        public async void StoragePermissionsMsg()
        {
            await DisplayAlert("You denied permission to write to storage.", "You cannot save and email the survey image. This App will now exit", "OK");
            System.Environment.Exit(0);
        }

The problem is that the StoragePermissions Msg() is called before the StoragePermissionsWriteCheck() is completed. I tried a .Wait() on the call to StoragePermissionsWriteCheck(), and make it task, but now the App hangs.

Not sure how to fix this.

listview data is not getting scrolled horizontally

$
0
0

Hello,
Below is the code the display the user registration details using listview in xamarin forms, but here the columns till username are only displayed ,the listview scroll function is not working ,please help. the scroll function required here is in both directions like vertical and horizontal
Thanks

<ListView.HeaderTemplate>


<Grid.RowDefinitions>

                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="50" />
                                <ColumnDefinition Width="100" />
                                <ColumnDefinition Width="100" />
                                <ColumnDefinition Width="50" />
                                <ColumnDefinition Width="50" />
                                <ColumnDefinition Width="150" />
                            <ColumnDefinition Width="50" />
                        </Grid.ColumnDefinitions>
                            <Label Grid.Column="0"  Text="Id" TextColor="Blue" />
                            <Label Grid.Column="1"  Text="Role" TextColor="Blue" />
                            <Label Grid.Column="2" Text="Name"  TextColor="Blue"/>
                            <Label Grid.Column="3"  Text="Username"  TextColor="Blue"/>
                            <Label Grid.Column="4" Text="Password" TextColor="Blue" />
                            <Label Grid.Column="5"  Text="Email" TextColor="Blue" />

                        </Grid>
                    </DataTemplate>
                </ListView.HeaderTemplate>

                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Grid  HorizontalOptions="CenterAndExpand">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="100" />
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="50" />
                                <ColumnDefinition Width="100" />
                                <ColumnDefinition Width="100" />
                                <ColumnDefinition Width="50" />
                                <ColumnDefinition Width="50" />
                                <ColumnDefinition Width="150" />


                            </Grid.ColumnDefinitions>
                                <Label Grid.Column="0" Text="{Binding userId}" />
                                <Label Grid.Column="1" Text="{Binding rolename}" />
                                <Label Grid.Column="2" Text="{Binding name}" />
                                <Label Grid.Column="3" Text="{Binding username}" />
                                <Label Grid.Column="4" Text="{Binding password}" />
                                <Label Grid.Column="5" Text="{Binding email}" />

                        </Grid>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

How to keep constant height of items in collection view

$
0
0

Hi ,
I am using collection view , and giving ItemSizingStrategy="MeasureAllItems". also I tried **ItemSizingStrategy="MeasureFirstItem"
** But height of items in collection view varies.
Is it possible to have a constant height of all item in collection view. How to keep constant height in collection view

OCR library for Xamarin forms

$
0
0

Hi All,

Can someone tell me any nuget package for OCR in xamarin forms

login using OTP

$
0
0

hello, i used OTP by sending verification number to user's phone number, and he can login to my app, my question is how i can checked user logedin before in app and redirect to main page, or if its firs time i show login page to him/her. i mean where should i store the token and how i should autherize token to let him go inside app


Image Source always picking image from cache.

$
0
0

Hi , I am using Image control in Xamarin forms android app. Used at two places one on hamburger slider and another on a content page. i am resolving image from webapi and using the code below:
private void OnPresentedChanged(object sender, EventArgs e)
{

            ImgProfile.Source = new UriImageSource()
            {
                Uri = new Uri(Constants.ProfilePicUrl),
                CachingEnabled = true,
                CacheValidity = new TimeSpan(5,0,0,0)
            };
        }

I tried aove code with both the conditions CachingEnabled = true/false . Here is what I observed:

  1. CachingEnabled = False : Each time the image control flickers and reloads the image. I can see a time gap of second or two between image reload from web url. Similary in the slider menu.
  2. CachingEnabled = true: My image control keeps on displaying the cached version even if the url has newer/different image, as its profile page and user can change his/her profile image N times a day.

So #1 solves my problem but the flickering part is annoying. Also please note , profile image is taken and uploaded from camera so there no way of uploading a customized image with lesser size to eliminate the delay..

I hope , my problem is clear to you guys.

Help making a focus timer app(help make the timer countdown)

$
0
0
public partial class MainPage : ContentPage

{

private System.Timers.Timer \_timer;

private int count = 0;



public MainPage()

{

InitializeComponent();

}

void Main()

{

\_timer = new System.Timers.Timer();

//trigger event every second

\_timer.Interval = 1000;

\_timer.Elapsed += OnTimedEvent;



}

private void OnTimedEvent(object sender, EventArgs e) {

count--;

\_timer.Enabled = true;



TimerLabel.Text = count.ToString();

if (count==0)

{

\_timer.Stop();

}

}

private void IncrementCounterClicked(object sender, EventArgs e)

{

count++;

TimerLabel.Text = count.ToString();

}

private void IncrementCounterClicked\_1(object sender, EventArgs e)

{



count+=5;

TimerLabel.Text = count.ToString();

}

private void ClearClicked(object sender, EventArgs e)

{



count = 0;

TimerLabel.Text = count.ToString();

}

}

}

**And my main page:**



<Label Text="00:00"

HorizontalOptions="Center"

FontSize="Title"

x:Name="TimerLabel"

TextColor="Silver"





\> </Label>

<Button Text="Start"

Clicked="OnTimedEvent"

FontSize="Body"

WidthRequest="80"

BackgroundColor="CornflowerBlue"

HorizontalOptions="Center"



\></Button>



<Button Text="+1"

Clicked="IncrementCounterClicked"

FontSize="Body"

WidthRequest="50"

BackgroundColor="CornflowerBlue"

HorizontalOptions="Center"



\></Button>



<Button Text="+5"

Clicked="IncrementCounterClicked\_1"

FontSize="Body"

WidthRequest="50"

BackgroundColor="CornflowerBlue"

HorizontalOptions="Center"

\></Button>



<Button Text="Clear"

Clicked="ClearClicked"

FontSize="Body"

WidthRequest="80"

BackgroundColor="CornflowerBlue"

HorizontalOptions="Center"

\></Button>

</StackLayout>

Ive really got no idea how to get it working or what to do. Im stuck and ive no idea where to find help

Discovering all devices connected to my network

$
0
0

Hi..
I want to create an app where I need to find devices connected to my wifi network using xamarin form

How to do SSL certificate pinning in Xamarin forms?

$
0
0

Hi all, I want to implement SSL certificate pinning with server using xamarin forms. Could any one please share me the code

How to export information to a contact, xamarin.forms

$
0
0

I have a bunch of info and entries, and I want to create a button with a function that exports all that info into a contact and save it.

Viewing all 79144 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>