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

How to achieve Geofencing in xamarin forms?

$
0
0

Hi Everyone,
I need to achieve the Geofencing functionality for my app. Suppose there will be a certain location and a user is moving to that location. When the user is out of that particular location it will send a reminder or something else. I have gone through some sample projects- https://github.com/rdelrosario/xamarin-plugins/tree/master/Geofence
in this project there are some plugins which are deprecates from Nuget.
https://allancritchie.net/posts/introducingshiny
The sample is not working.

I didn't get any exact information. Can someone please help me out regarding this?

help


input type="file" doesn't work on Xamarin.Forms Webview (Android)

$
0
0

I have a WebView that points to a website, something like this:

var browser = new WebView {
Source = "www.sometlink.com/uploadimage"
};

This is a html page where it allow users to upload some images. The html element is just a simple:

This works well on iOS, but not on Android. The "Choose File" button does nothing at all (no pop out etc.)

After doing some extensive research, it appears the problem as described here: http://stackoverflow.com/questions/4944102/android-webview-file-input-field-filechooser-doesnt-show-up

The suggested solution works if I switch to Xamarin.Android, but how do I duplicate the solution using Xamarin.Forms?

Are there alternate In-App-Billing library/plugins?

$
0
0

Hello, so many people seem to use this plugin by @JamesMontemagno - https://github.com/jamesmontemagno/InAppBillingPlugin

I don't think that is being maintained or amended any longer and cannot get further info or responses on project in Github.

Is/are there any similar alternate IAP plugins/libraries out there worth considering and using? For iOS and Android.
Something that handles subscriptions well, allowing the user to purchase a subscription, auto-renew and cancel a subscription IN-APP.
A commercial/bought product would be considered too.

Thanks

iOS simulator failing - Failed to install

$
0
0

Hi there, hope you all well. I would appreciate a little help here please. he he. I have visual studio on my Win 10 PC. and a MAC I can pair with 100%.

when I try and run even a new "empty" xamarin.forms project. say a tabbed project. I keep on getting this error when trying a iPhone simulator.

any help would really be appreciated a lot!

thanks,
Derrick


Xamarin Simulator

Failed to install //Users/Mac/Library/Caches/Xamarin/mtbs/builds/App2.iOS/7eb936965422a1f08706700aab359b22/bin/iPhoneSimulator/Debug/App2.iOS.app to A1FF81F5-E9EE-4432-A328-0F53911241B8. The app directory '/Users/Mac/Library/Caches/Xamarin/mtbs/builds/App2.iOS/7eb936965422a1f08706700aab359b22/bin/iPhoneSimulator/Debug/App2.iOS.app' does not exist.

OK

How to hover a image half on the page in a custom menu bar?

$
0
0

Hi everyone,
I am working on a project in which I need to create a custom menu bar. The challenge i am facing is while giving the left margin in minus is being hover on a page in IOS but not on android.
Below is the code snippet and screenshots as well.

    <?xml version="1.0" encoding="utf-8" ?>
        <pages:PopupPage  xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
              xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
              xmlns:local="clr-namespace:InspireApp.Views"
              xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup" 
              xmlns:local1="clr-namespace:InspireApp" xmlns:controls="clr-namespace:ImageCircle.Forms.Plugin.Abstractions;                  
    assembly=ImageCircle.Forms.Plugin"
              BackgroundColor="Transparent"
              x:Class="InspireApp.Views.MenuBar"
              >
     <pages:PopupPage.Animation>
        <animations:ScaleAnimation 
          PositionIn="Right"
          PositionOut="Right"
          ScaleIn="1"
          ScaleOut="0.8"
       DurationIn="400"
       DurationOut="300"
       EasingIn="SinOut"
       EasingOut="SinIn"
       HasBackgroundAnimation="True"/>
     </pages:PopupPage.Animation>
        <StackLayout Orientation="Vertical" VerticalOptions="FillAndExpand" WidthRequest="300" 
             BackgroundColor="White"
             HorizontalOptions="EndAndExpand" Padding="0, 0, 0, 0">
            <StackLayout Orientation="Vertical" HeightRequest="180" BackgroundColor="LightGray">
             <StackLayout Orientation="Horizontal" HorizontalOptions="End" VerticalOptions="Start" Margin="10">
                    <Image x:Name="CLoseImg" Source="icon_close" HorizontalOptions="End" HeightRequest="30" VerticalOptions="Center">
                        <Image.GestureRecognizers>
                           <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
                       </Image.GestureRecognizers>
                  </Image>
             </StackLayout>
               <StackLayout Orientation="Horizontal" VerticalOptions="EndAndExpand">

                  <controls:CircleImage Aspect="AspectFill"
                                       Source="Dummy_User.png" Margin="-30,20,0,-20" HeightRequest="100" WidthRequest="100" BackgroundColor="Transparent"
                                  VerticalOptions="End" HorizontalOptions="StartAndExpand" />


            <StackLayout Orientation="Vertical" Spacing="0" HorizontalOptions="CenterAndExpand" VerticalOptions="Center">
                <Label x:Name="lblFirst" Text="William" TextColor="Black" FontAttributes="Bold" HorizontalOptions="Start" VerticalOptions="StartAndExpand" FontSize="Small"/>
                <Label x:Name="lblLast" Text="Turner" TextColor="Black" FontAttributes="Bold" HorizontalOptions="Start" VerticalOptions="StartAndExpand" FontSize="Medium"/>
            </StackLayout>
            <controls:CircleImage   Margin="-20,10,0,-10"
                                  Source="icon_settings.png" HorizontalOptions="EndAndExpand" 
                                  VerticalOptions="End" HeightRequest="50">
                <controls:CircleImage.GestureRecognizers>
                    <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped_1"/>
                </controls:CircleImage.GestureRecognizers>
            </controls:CircleImage>
        </StackLayout>

    </StackLayout>

    <StackLayout VerticalOptions="End" >
        <Label Text="Switch to responsive web application" TextColor="#179CA6" HorizontalOptions="Center" FontAttributes="None">
            <Label.GestureRecognizers>
                <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped_2"/>
            </Label.GestureRecognizers>
        </Label>
    </StackLayout>
    <Frame VerticalOptions="End" BackgroundColor="LightGray" >
        <Label Text="Sign Out" TextColor="Black" FontAttributes="Bold" HorizontalOptions="FillAndExpand" 
               HorizontalTextAlignment="Center" VerticalOptions="FillAndExpand"/>
    </Frame>
</StackLayout>


any idea?

Image not show on device

$
0
0


<Image.Source>

</Image.Source>

HinhAnh2 = "http://mywebsite.com/someimage.png"

Run debug, It show image correctly

When build release to run on device, the images not show

Can you help me, how to build the release or I need any permission.
Thank you.

LOOP THRU ENTRIES FROM VIEWMODEL

$
0
0

I'm fairly new to Xamarin, but have been making good progress. At present, I', essentially adding some pull notification logic to my app, so I've created a Timer on my opening page. It is to display an alert to the user indicating when a new entry has been placed on their list. The page CS code is as follows:

    public DriverPage()
    {
        InitializeComponent();

        Device.StartTimer(new TimeSpan(0,0,0,60), () =>
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                var jobAllocList = new AllocationsViewModel();

                foreach (var allocentry in jobAllocList.DriverAllocations)
                {
                    if (allocentry.JobStatus.Equals(0))
                    {
                        DisplayAlert("New Job Allocation", "You have just been allocated the following job" + Environment.NewLine + 
                                                           "Job Id:    " + allocentry.JobId + Environment.NewLine + 
                                                           "Customer:  " + allocentry.PayCustomer + Environment.NewLine + 
                                                           "From:      " + allocentry.FreightFrom + Environment.NewLine + 
                                                           "           " + allocentry.FromSuburb + Environment.NewLine + 
                                                           "To:        " + allocentry.FreightTo + Environment.NewLine + 
                                                           "           " + allocentry.ToSuburb, "OK");
                        allocentry.JobStatus = 1;
                        Task.Run(async () => { await jobAllocList.SetStatus(); });
                    }
                }
            });
            return true;
        });
...
}            

The relevant ViewModel code is as follows:

    ObservableCollection<DriverAllocation> allocations = new ObservableCollection<DriverAllocation>();
    public ObservableCollection<DriverAllocation> DriverAllocations
    {
        get { return allocations; }
        set { SetProperty(ref allocations, value, "DriverAllocations"); }
    }

    public ICollection<DriverAllocation> list;

    async Task ExecuteRefreshCommand()
    {
        if (IsBusy) return;
        IsBusy = true;

        try
        {
            var table = App.CloudService.GetTable<DriverAllocation>(); 
            list = await table.ReadAllItemsAsync();

            IEnumerable<DriverAllocation> sortedList =
                from alloc in list
                where alloc.UserId == "98"
                orderby alloc.JobId ascending
                select alloc;

            while (DriverAllocations.Count > 0) DriverAllocations.RemoveAt(0);

            foreach (var entry in sortedList)
                DriverAllocations.Add(entry);
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"[DriverAllocations] Error loading entries: {ex.Message}");
        }
        finally
        {
            IsBusy = false;
        }
    }

What I am seeing (using debug etc) is that the AllocationsViewModel is being initialized successfully, and the ExecuteRefreshCommand is successfully called. I can even see that just as it completes, the DriverAllocations.Count (using immediate window) is 10. But when control returns to the page and the "foreach (var allocentry in jobAllocList.DriverAllocations)" statement executes, jobAllocList.DriverAllocations.Count is 0.

I'm wondering is this is an ASYNC issue, and that the foreach statement is not waiting for the ViewModel refresh to complete, though using debug this doesn't seem to be the case... Or is it something else like the foreach does not have addressability to the returned ViewModel data, and if so, why... Or perhaps something else...

Accessing iCloud in XF using Dependency Service

$
0
0

I was following @LandLu post in this forum thread.

The following line is giving a Null Exception:

//Get the iCloud's url
var filePath = NSFileManager.DefaultManager.GetUrlForUbiquityContainer(null).Append("Documents", true);

Even replacing the 'null' in the argument of GetUrlForUbiquityContainer with my container id which is of the form "iCloud.com.companyname.appname" didn't help.

What am I doing wrong?

I am using automatic provisioning. Is that wrong?

Also one more question:
In the following code in the same post, what is the namespace of File and Path?

//Here I write a test string in this document folder
File.WriteAllText(Path.Combine(filePath.Path, "test.txt"), "test");


INSTALL_FAILED_INVALID_APK: Failed to extract native libraries, res=-2

$
0
0

Hi!

After upgrading to Version 8.7 (build 2037)
I can't distribute my Android APK, it works fine when running on Release-mode thru VS to device but when building APK and trying to install I get
"INSTALL_FAILED_INVALID_APK: Failed to extract native libraries, res=-2"

Anybody experienced anythings similar ?

Info (16393) / Finsky: [10916] dda.a(14): Decompressing com.mobisma.Truckify (com.mobisma.Truckify) format 1 Info (16393) / Finsky: [11152] his.run(25): Stored data usage stats for package com.mobisma.Truckify; completed bytes: 21096891. Info (16393) / Finsky: [10916] dda.a(21): com.mobisma.Truckify (com.mobisma.Truckify) (58955507 bytes) copied successfully in 2381 ms Info (16393) / Finsky: [2] ntd.run(14): IT: Removed com.mobisma.Truckify from ResourceManager for copy success. Info (16393) / Finsky: [2] ntf.a(7): IT: Successfully copied APK to update com.mobisma.Truckify (adid: com.mobisma.Truckify , isid: _Z6lTNC_TnuH2_mkbYOVow) Info (16393) / Finsky: [2] nua.b(9): IT: com.mobisma.Truckify to state 40 Info (16393) / Finsky: [10923] nrh.accept(22): IT: starting next download: package=com.mobisma.Truckify Info (16393) / Finsky: [10923] nqz.a(3): Handling streamingComplete for com.mobisma.Truckify gid: 0 Info (16393) / Finsky: [10923] nua.c(56): IT: Begin install of com.mobisma.Truckify (isid: _Z6lTNC_TnuH2_mkbYOVow) Info (16393) / Finsky: [10923] nra.a(188): Installer: Notifying status update. package=com.mobisma.Truckify, status=INSTALLING Info (16393) / Finsky: [10962] odj.b(52): IQ: Notifying installation update. package=com.mobisma.Truckify, status=INSTALLING Info (16393) / Finsky: [2] hub.a(11): Selecting account [g2cNcEkt4qyAHQHQHBj4L4nIXedQdYObSnt3w1p78X4] for package com.mobisma.Truckify. overriding=[true] Info (16393) / Finsky: [2] hub.a(11): Selecting account [g2cNcEkt4qyAHQHQHBj4L4nIXedQdYObSnt3w1p78X4] for package com.mobisma.Truckify. overriding=[true] Info (16393) / Finsky: [2] hub.a(11): Selecting account [g2cNcEkt4qyAHQHQHBj4L4nIXedQdYObSnt3w1p78X4] for package com.mobisma.Truckify. overriding=[true] Info (16393) / Finsky: [2] hub.a(11): Selecting account [g2cNcEkt4qyAHQHQHBj4L4nIXedQdYObSnt3w1p78X4] for package com.mobisma.Truckify. overriding=[true] Info (25196) / Finsky:download_service: [11448] juk.a(20): onRemove(request_id=334, files_to_download=1, group_id=com.mobisma.Truckify, display_data[invisible=false, title=Truckify], network_restrictions=4, status=succeeded, bytes_downloaded=21096891, retry[count=0, next_retry=n/a]) Error (16393) / Finsky: [2] tyc.onReceive(17): Error -504 while installing com.mobisma.Truckify: INSTALL_FAILED_INVALID_APK: Failed to extract native libraries, res=-2 Warning (16393) / Finsky: [2] ntx.a(17): IT: Install failure of com.mobisma.Truckify (isid: _Z6lTNC_TnuH2_mkbYOVow): -504, Exception: n/a Warning (16393) / Finsky: [2] nua.a(192): IT: Cleanup running installation of com.mobisma.Truckify (com.mobisma.Truckify) Info (16393) / Finsky: [10909] nrz.run(12): IT: Running resource fetching of com.mobisma.Truckify canceled. Info (16393) / Finsky: [2] nra.b(32): Installer: stopping tracking of task: com.mobisma.Truckify Info (16393) / Finsky: [2] nra.a(188): Installer: Notifying status update. package=com.mobisma.Truckify, status=INSTALL_ERROR Info (16393) / Finsky: [10962] odj.b(52): IQ: Notifying installation update. package=com.mobisma.Truckify, status=INSTALL_ERROR Info (16393) / Finsky: [2] hub.a(11): Selecting account [g2cNcEkt4qyAHQHQHBj4L4nIXedQdYObSnt3w1p78X4] for package com.mobisma.Truckify. overriding=[true] Info (16393) / Finsky: [2] hub.a(11): Selecting account [g2cNcEkt4qyAHQHQHBj4L4nIXedQdYObSnt3w1p78X4] for package com.mobisma.Truckify. overriding=[true] Info (16393) / Finsky: [2] hub.a(11): Selecting account [g2cNcEkt4qyAHQHQHBj4L4nIXedQdYObSnt3w1p78X4] for package com.mobisma.Truckify. overriding=[true] Info (16393) / Finsky: [2] hub.a(11): Selecting account [g2cNcEkt4qyAHQHQHBj4L4nIXedQdYObSnt3w1p78X4] for package com.mobisma.Truckify. overriding=[true]



help with calendar

$
0
0

Hello everyone

I am using this plugin (https://github.com/lilcodelab/Xamarin.Plugin.Calendar), for calendar event,
I am also using this (https://github.com/f-miyu/Plugin.CloudFirestore)

Ok so I upload my event to firebase, and everything works beautiful and dandy, but when I read my Document to add my data to my calendar I cant, it wont add.

So here I am using the messeging center, to get my pet ID back from the other page like this

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

            petControl.Id = id;
            Preferences.Set("id", id);
            petControl.Nombre_Mascota = Nombre;
            petControl.FechaControl = Date;
            petControl.HoraControl = Time;
            petControl.LugarControl = ControlLugar.Text;
            petControl.TipoControl = TipoDeControlPicker.SelectedItem.ToString();

            await CrossCloudFirestore.Current
                         .Instance
                         .GetCollection("PetControls")
                         .AddDocumentAsync(petControl);

            await Navigation.PopAsync();
            MessagingCenter.Send(this, "Message", petControl.Id);
            //CalendarViewModel.getData();

        }
MessagingCenter.Subscribe<KeppingTrack, string>(this, "Message", async (sender, helper) => {
                this.helper = helper;

                //helper == id
                if (!string.IsNullOrEmpty(helper)) {

                    var query = await CrossCloudFirestore.Current
                                                         .Instance
                                                         .GetCollection("PetControls")
                                                         .WhereEqualsTo("Id", helper)
                                                         .GetDocumentsAsync();

                    string uid = string.Empty;

                    foreach (var item in query.Documents) {
                        uid = item.Id;
                    }

                    var document = await CrossCloudFirestore.Current
                                                .Instance
                                                .GetCollection("PetControls")
                                                .GetDocument(uid)
                                                .GetDocumentAsync();

                    model = document.ToObject<PetControl>();


                    Events = new EventCollection {
                        [DateTime.Now] = new List<PetControl>
                        {
                            new PetControl { Nombre_Mascota = model.Nombre_Mascota, TipoControl = model.TipoControl,
                                            HoraControl = model.HoraControl, FechaControl = model.FechaControl,
                                            LugarControl = model.LugarControl},

                        },
                    };
                }
            });
        }

but for some reason it doesn't add anything

UI

<controls:Calendar x:Name="calendar" Events="{Binding Events}">
                <controls:Calendar.EventTemplate>
                    <DataTemplate>
                        <StackLayout Padding="15,0,0,0">
                            <Label Text="{Binding Nombre_Mascota}"
                                   FontAttributes="Bold"
                                   FontSize="Medium" />
                            <Label Text="{Binding TipoControl}"
                                   FontSize="Small"
                                   LineBreakMode="WordWrap" />
                        </StackLayout>
                    </DataTemplate>
                </controls:Calendar.EventTemplate>
            </controls:Calendar>

Problem with SmtpClient.Send method in App Store Review Team.

$
0
0

I'm having trouble publishing a Xamarin.Forms app in the App Store. I am using Visual Studio 2019 (16.7.0), Xamarin Forms 4.6.0.1141.

I have a function responsible for sending e-mails, in short it works for me, but not in the App Store Review Team.

I tested it on the iOS simulator in Visual Studio, also on a device connected to my laptop (Windows and Hot Reload), and also directly on the device using the Install On Air website (I created a new PP, with the addition of the UDID and then built the release).

Below code:
https://snippet.host/csuk

I get a notification that the e-mail has been sent, but the App Store Review Team sends a screenshot showing that there is an error (DisplayAlert("Error", "Unable to send message, please check your internet connection and try again.", "OK")).

The credentials for the SMTP server are constants and definitely working. App Store Review Team has Internet access.

how to distinguish between two items in a json encoded string

$
0
0

code is:

  public async Task UploadNewSnapAsync(string item , string item2)
    {
        HttpClientHandler handler = new HttpClientHandler();
        handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };


        client5 = new HttpClient(handler);
        client5.MaxResponseContentBufferSize = 256000;
        var uri = new Uri(string.Format(Constants.RestUrl, string.Empty));


       var json = JsonConvert.SerializeObject(item);



       var json1 = JsonConvert.SerializeObject(item);


        var formContent = new MultipartFormDataContent
          {
            // Send form text values here
               { new StringContent(json, Encoding.UTF8, "application/json")},
               { new StringContent(json1, Encoding.UTF8, "application/json")}
        };
        // Send Image Here
        formContent.Headers.ContentType.MediaType = "multipart/form-data";
        HttpResponseMessage response = null;

        response = await client5.PostAsync(uri, formContent);



        if (response.IsSuccessStatusCode)
        {
            Debug.WriteLine(@"                TodoItem successfully saved.");

        }
    }

json1 is image 1, jason 2 is image 2.

How can we tell the json receiver there are two images and where they split at?

I tried the following:

            { new StringContent(json, Encoding.UTF8, "image1")},
            { new StringContent(json1, Encoding.UTF8, "image2")}

and it gave me an error, image1 unknown data type

Rick

How to hide NavigationBar in TabbedPage.Children?

$
0
0

NavigationPage.HasNavigationBar="False" not work.

How to determine iOS version number in Xamarin?

$
0
0

How to determine iOS version number in Xamarin?
Who knows, please tell me, thank you!

How to generate .IPA file

$
0
0

Hi,
How to generate .ipa file in xamarin forms in Visual Studio..

Thanks
Lucy


Error on testing App Groups on device

$
0
0

Hello
I have installed the last version of xamarin forms 4.8.0.1269
I'm trying to add today extension to my app, but I have 2 problems:
1. This error when I try to test the app on my physical iPhone: error MT1006: Could not install the application 'xxxxx' on the device 'xxxxx': Your code signing/provisioning profiles are not correctly configured. Probably you have an entitlement not supported by your current provisioning profile, or your device is not part of the current provisioning profile. Please check the iOS Device Log for details (error: 0xe8008016).
2. I can test app on iPhone Simulator but cannot access to App-Groups with NSUserDefaults

For the first problem I have created the provisioning profiles for both host app and extension app and enabled the App Group:
Host app BundleIdentifier: com.MyCompany.MyApp
Ext app BundleIdentifier: com.MyCompany.MyApp.MyExt
App Group: group.com.MyCompany.MyApp

Both apps have Entitlements.plist file referenced and AppGroup enabled on group.com.MyCompany.MyApp
If I disable the AppGroup flag from Entitlements.plist the app runs on device correctly.

For the second problem I have used this simple code lines to write and read data:

var shared = new NSUserDefaults("group.com.MyCompany.MyApp", NSUserDefaultsType.SuiteName);
shared.SetString("test data", "mydata");
shared.Synchronize();

var shared = new NSUserDefaults("group.com.MyCompany.MyApp", NSUserDefaultsType.SuiteName);
extensionLabel.Text = "Key: " + shared.StringForKey("mydata");

Can anyone help me please?

Thanks

How to destroy a view and collect the garbage when navigating backward?

$
0
0

Sometimes, the user encounter a crash when leaving the urhosurface view and opening it again.
I have described that here:
https://forums.xamarin.com/discussion/183748/cannot-show-urhosharp-surface-multiple-times#latest

Because I create a new view when I open the page:

        async void OnButtonSkyMapClicked(object sender, EventArgs args)
        {
            await Navigation.PushAsync(new SkyUrhoSurface());
        }

I had the idea to create the page only once and to PushAsync it several times:
https://forums.xamarin.com/discussion/184247/urhosharp-how-to-instanciate-a-urhosurface-only-once#latest

But that does not work: The page is drawn only once, the second time and after, the page remains black. So I had to give up that solution (it is too bad because I would not need to load the view and the view model many times)

I believe the app crashes because the previous view was not destroyed and garbage collected. I guess the app would not crash if I destroy the page when navigating back and if I collect the garbage.

What do you think?
How can I do that?

cannot show urhosharp surface multiple times

$
0
0

When the user open the view, navigate backwards and open the view a second time, the app crashes.
Any idea how to go around this issue?
Idealy, I would like to call:

skyUrho = await urhoSurface.Show<SkyUrho>(urhoApp);

only once in the constructor but that is not possible as it is an async call.

This is the code behind of the view:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

using AlmicantaratXF.ViewModels;
using AlmicantaratXF.Model;

namespace AlmicantaratXF.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class SkyUrhoSurface : ContentPage
    {
        private Sight currentSight;
        private SkyUrho skyUrho;
        private INavigation navigation;
        private Urho.ApplicationOptions urhoApp;
        public SkyUrhoSurface()
        {
            InitializeComponent();
            this.currentSight = null;
            urhoApp = new Urho.ApplicationOptions(assetsFolder: "Data");
        }
        public SkyUrhoSurface(Sight currentSight, INavigation navigation)
        {
            InitializeComponent();
            this.currentSight = currentSight;
            this.navigation = navigation;
            urhoApp = new Urho.ApplicationOptions(assetsFolder: "Data");
        }
        protected override async void OnAppearing()
        {
            base.OnAppearing();
            skyUrho = await urhoSurface.Show<SkyUrho>(urhoApp);
          //SkyUrho skyUrho = new SkyUrho(new Urho.ApplicationOptions(assetsFolder: "Data"));
            skyUrho.PageVisible = true;
            skyUrho.StarSelection = (currentSight != null);
            buttonShootThisBody.BindingContext = skyUrho;
            labelLat.BindingContext = skyUrho;
            labelLon.BindingContext = skyUrho;
            labelAltitude.BindingContext = skyUrho;
            labelAzimuth.BindingContext = skyUrho;
            labelBodysName.BindingContext = skyUrho;
            labelBodysDirection.BindingContext = skyUrho;
            labelGPSStatus.BindingContext = skyUrho;
            //activityIndicator.BindingContext = skyUrho;
            activityIndicator.IsVisible = false;
            activityIndicator.IsRunning = false;
        }
        protected override async void OnDisappearing()
        {
            base.OnDisappearing();
            if (skyUrho != null)
                skyUrho.PageVisible = false;
        }
        void OnCheckBoxNamesChanged(object sender, CheckedChangedEventArgs e)
            {
                if(skyUrho!=null)
                    skyUrho.Names = e.Value;
            }
        void OnButtonShootThisBodyClicked(object sender, EventArgs args)
        {
            if(skyUrho!=null)
                if(skyUrho.SelectedStar!=null)
                    this.currentSight.StarID = (int)skyUrho.SelectedStar;
            navigation.PopAsync();
        }
    }
}

How to Change .Navigation.PushModalAsync animation direction?

$
0
0

How to Change .Navigation.PushModalAsync animation direction?

Cannot create a user control with two way binding to view model property names

$
0
0

My objective is to create a user control containing a basic Entry control that will update a specified property in my view model.
I have been unable to bind the user control to the property name in my view model unless the view model property name is exactly the same as the property in the user control. This defeats the purpose of a reusable two way reusable control.
I suspect I'm just missing a key concept.

My expectation is that I should be able to add one or more of my UserEditors to a page and bind it to various string properties in the view model, and the property the UserEditor gets/sets should be the property I specify in the {Binding } for the UserEditor.

I have created a simple PCL project to test with. I would be very grateful if someone can get me on the correct track with this. I have exhausted all other resources to come to grips with this. I can provide a zip file of the VS2015 solution, however its pretty big (65MB) with all the XAM stuff.

Here are all the pieces:
UserEditor.xaml:

    <?xml version="1.0" encoding="UTF-8"?>
    <ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
                 x:Class="UserControl.UserEditor">
      <ContentView.Content>
            <StackLayout Orientation="Vertical" Margin="0,0,0,10" >
                <Entry x:Name="TextEntry" 
                       Text="{Binding Text}"
                       HorizontalOptions="Fill"/>
            </StackLayout>
        </ContentView.Content>
    </ContentView>

UserEditor.xaml.cs

    using System;
    using System.Linq;

    using Xamarin.Forms;

    namespace UserControl
    {
        public partial class UserEditor : ContentView
        {
            //Bindable property for Text
            public static readonly BindableProperty TextProperty =
                BindableProperty.Create("Text",
                    typeof(string),
                    typeof(UserEditor),
                    string.Empty,
                    BindingMode.TwoWay,
                    null,
                    OnTextPropertyChanged,
                    null,
                    null,
                    null);

            public static void OnTextPropertyChanged(BindableObject bindable, object oldValue, object newValue)
            {
                var control = bindable as UserEditor;
                if (control == null) return;
                control.TextEntry.Text = newValue.ToString();
            }

            public UserEditor()
            {
                InitializeComponent();
            }

            public string Text
            {
                get
                {
                    return (string)GetValue(TextProperty);
                }
                set
                {
                    SetValue(TextProperty, value);
                }
            }
        }
    }

MainPageViewModel.cs

using System;
using System.ComponentModel;
using System.Linq;

namespace UserControl
{
    class MainPageViewModel : INotifyPropertyChanged

    {
        public event PropertyChangedEventHandler PropertyChanged;

        public MainPageViewModel()
        {

        }

        protected void OnPropertyChanged(string name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        string textProperyInVM = "Initial value";
        public string TextPropertyInVm
        {
            get
            {
                return textProperyInVM;
            }
            set
            {
                textProperyInVM = value;
                OnPropertyChanged("TextPropertyInVm");

            }
        }
    }
}

MainPage.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:UserControl"
             x:Class="UserControl.MainPage">

    <!--//Page binding context is set to the view model in the page contructor.-->
    <StackLayout Orientation="Vertical">
    <Label Text="Binding viewmodel properties to user control"  />
        <!--//Label is bound to ViewModel field named TextPropertyInVm-->
        <Label Text="{Binding TextPropertyInVm}" ></Label>

        <!--//UserEditor custom control is bound to ViewModel field named TextPropertyInVm
        //User editor will not see the view model property.
        //User editor ALWAYS wants to work with a property named "Text"
        //User editor neither reads nor updates the view model property specified in the Binding -->
        <!--
        Text changes in the user control cause this error:
        [0:] Binding: 'Text' property not found on 'UserControl.MainPageViewModel', target property: 'Xamarin.Forms.Entry.Text'
        -->
        <local:UserEditor Text="{Binding TextPropertyInVM, Mode=TwoWay}"></local:UserEditor>
    </StackLayout>
</ContentPage>

MainPage.xaml.cs

using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace UserControl
{
    public partial class MainPage : ContentPage
    {
        private MainPageViewModel vm;
        public MainPage()
        {
            InitializeComponent();
            //instantiate and bind this page to a new view model.
            vm = new MainPageViewModel();
            this.BindingContext = vm;
        }
    }
}
Viewing all 79144 articles
Browse latest View live


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