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

Searchbar combined with dropdown-list of suggestions to autocomplete the search with

$
0
0

Hello,

I'd like to do something like shown in the attached picture. Do you guys have any suggestions on how I should go about doing it, do I need to write my own control? The drop down and the search bar can be separate components, I just want a dropdown-list to pop.


Button with Image and Text

$
0
0

Hi,
I have a Button with an Image inside, but my users think that a picture with text would be better. The problem is, when the resolution is not too big, text and image takes too much place. A better solution is, when the display/resolution is big enough, show the picture with text otherwise the image only. I took a look into the VisualStateManager stuff, but do not know how I to trigger the different states by changing the resolution. This XAML style I place into the button style:

               <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup x:Name="ShowTextStates">
                        <VisualState x:Name="ShowText">
                            <VisualState.Setters>
                                <Setter Property="Text" Value="Test test test..." />
                            </VisualState.Setters>
                        </VisualState>
                        <VisualState x:Name="HideText">
                            <VisualState.Setters>
                                <Setter Property="Text" Value="" />
                            </VisualState.Setters>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>

How can I solve this problem? Any suggestions? Thank you!

How to change the background color of the text/ sub string on swiping the text/sub string?

$
0
0

I need implementation similar to highlighting the text inside the paragraph on selecting the particular text.

HotReload LiveReload LiveXaml [Mac] [Windows] [nuget package] [opensource]

Pickers opens box twice when focused after focus an entry

$
0
0

Hi everyone!!
I have a big issue that I can't solve from myself.

like the title says, in my android app (using xamarin.forms 3.4.0.1009999 after I updated from a very old version) when I select an entry, then tap over a picker, it opens twice.
A workaround I found is to place the picker in a StackLayout.. but when the picker is in a grid this workaround doesn't work.

Searching into the web, this issue should be resolved in release 3.4.0.1 so.. any ideas?

thanks!!!

How to ask for Camera Permission on iOS if i revoked it ?

$
0
0

Hello,

i have an Permission Dependency Service, because i don't like to use CrossPermissions Plugin.
Now i don't know how to ask for the Camera Permission on iOS if i revoked it.
Can somebody help ?

ListView with over 200 Bindings

$
0
0

Is there a way to speed up the performance of ListView, which uses over 200 Bindings?

This is a list that uses mostly Label elements, I do not use images at all.

Firebase Messaging (FCM) OnMessageReceived Running Twice

$
0
0

Good day

I am using Firebase Messaging to send/Receive Push Notification on Android.

I've got the following implementation which is triggering OnMessageReceived twice on Android v 8.0, after rebooting the phone once, opening the app, rebooting the phone again and then sending myself a push notification.

Any ideas on what is causing this? I've looked online and found suggestions on removing any old GCM references which I have done already. The first time the app is built and deployed to the device, it doesn't happen and all subsequent push notifications seem fine. This just happens when the phone goes through the above mentioned reboot procedure. It may happen in other cases too but this has been my method to re-create the issue.

The App is compiled using

  • Xamarin.Forms 3.4.0.1008975
  • Xamarin.Firebase.Messaging 60.1142.1

If any further information is required, please ask me.

The code is as follows:

MainActivity.cs

using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Gms.Common;
using Android.OS;
using Android.Views;
using Plugin.Permissions;
using Android.Util;
using Android.Gms.Common.Apis;
using Android.Gms.Drive;
using Android.Runtime;
using System;

namespace App.Droid
{
    [Activity(Label = "App", Icon = "@drawable/launch_icon", LaunchMode = LaunchMode.SingleTop, Theme = "@style/MyTheme", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]

    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, GoogleApiClient.IConnectionCallbacks, GoogleApiClient.IOnConnectionFailedListener, IResultCallback
    {
        const string TAG = "MainActivity";
        const int REQUEST_CODE_RESOLUTION = 3;
        public static GoogleApiClient googleApiClient;
        public static byte CurrentGoogleDriveState = 0x00;

        internal static readonly string CHANNEL_ID = "default";
        internal static readonly int NOTIFICATION_ID = 100;

        protected override void OnCreate(Bundle bundle)
        {

            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);
                LoadApplication(new App("", ""));

            IsPlayServicesAvailable();
            CreateNotificationChannel();
        }

        void CreateNotificationChannel()
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                // Notification channels are new in API 26 (and not a part of the
                // support library). There is no need to create a notification
                // channel on older versions of Android.
                return;
            }

            var channel = new NotificationChannel(CHANNEL_ID,
                                                  "FCM Notifications",
                                                  NotificationImportance.Default)
            {

                Description = "Firebase Cloud Messages appear in this channel"
            };

            var notificationManager = (NotificationManager)GetSystemService(Android.Content.Context.NotificationService);
            notificationManager.CreateNotificationChannel(channel);
        }

        public bool IsPlayServicesAvailable()
        {
            int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this);
            if (resultCode != ConnectionResult.Success)
            {
                return false;
            }
            return true;
        }
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" package="--Redacted--" android:versionCode="--Redacted--" android:versionName="--Redacted--">
    <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="26" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.FLASHLIGHT" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-feature android:name="android.hardware.screen.landscape" />
    <uses-feature android:name="android.hardware.wifi" android:required="false" />
    <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
    <application android:label="--Redacted--" android:icon="@drawable/logo_cropped" android:allowBackup="true" android:largeHeap="true">
        <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
        <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="${applicationId}" />
            </intent-filter>
        </receiver>
        <meta-data android:name="android.max_aspect" android:value="2.1" />
    </application>
</manifest>

FirebaseRegistration.cs

using Android.App;
using Firebase.Iid;
using Android.Util;
using System;
using System.IO;
using Android.Content;

namespace App.Droid
{
    [Service]
    [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    public class MyFirebaseIIDService : FirebaseInstanceIdService
    {
        const string TAG = "MyFirebaseIIDService";
        public override void OnTokenRefresh()
        {
            base.OnTokenRefresh();

            var refreshedToken = FirebaseInstanceId.Instance.Token;
            Log.Debug(TAG, "Refreshed token: " + refreshedToken);
            SendRegistrationToServer(refreshedToken);

        }

        /// <summary>
        /// Sends the token to server.
        /// </summary>
        /// <param name="token">Token.</param>
        void SendRegistrationToServer(string token)
        {
            // My code to send the push notification ID to our backend
        }
    }
}

FirebaseMessaging.cs

using System;
using System.Globalization;
using Android.App;
using Android.Content;
using System.Linq;
using Firebase.Messaging;
using System.Collections.Generic;
using System.Threading.Tasks;
using Android.OS;
using static Android.App.ActivityManager;
using Android.Support.V4.App;

namespace App.Droid
{
    [Service]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
    public class MyFirebaseMessagingService : FirebaseMessagingService
    {
        const string TAG = "MyFirebaseMsgService";

        async public override void OnMessageReceived(RemoteMessage message)
        {
            base.OnMessageReceived(message);

            Console.WriteLine("["+this.GetType().FullName+"]\t\t\t\t Push Notification Received! \n\n" + Newtonsoft.Json.JsonConvert.SerializeObject(message));
        }
    }
}

AppCompatActivity in xamarin.Android ViewRenderer

$
0
0

Hi,
I am working on calendar events in my xamarin forms android app by using Com.Alamkanak.Weekview. I want to load calendar events in Content page. My code in Content page like

    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:controls="clr-namespace:App.CustomControls"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:local="clr-namespace:app.CustomControls">
        <ContentPage.Content>
                 <StackLayout Orientation="Vertical">
                    <ContentView>
                        <OnPlatform x:TypeArguments="View">
                            <OnPlatform.Android>
                                <local:CustomCalendarEvent/>
                            </OnPlatform.Android>
                        </OnPlatform>
                    </ContentView>
                </StackLayout>
              </ContentPage.Content>
    </ContentPage>

my CustomCalendarEvent is

public class CustomCalendarEvent : View{ }

my ViewRenderer is like

[assembly: ExportRenderer(typeof(CustomCalendarEvent), typeof(CustomCalendarEventRenderer))]
namespace App.Droid.CustomRenderers
{
    public class CustomCalendarEventRenderer : ViewRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
        {
            base.OnElementChanged(e);
            if (Control == null)
            {
                try
                {
                    var intent = new Intent(Forms.Context, typeof(Events));
                    Forms.Context.StartActivity(intent);

                    //var context = Xamarin.Forms.Forms.Context;
                    //LayoutInflater inflater = context.GetSystemService(Context.LayoutInflaterService) as LayoutInflater;
                    //var _view = inflater.Inflate(Resource.Layout.EventView, this, false);
                    //mWeekView = _view.FindViewById<WeekView>(Resource.Id.weekView);
                    //SetNativeControl(_view);
                }
                catch (Exception ex)
                {
                    string Message = ex.Message;
                }
            }    
        }
    }
}

and my Events activity is like

        public class Events : AppCompatActivity, WeekView.IEventClickListener, WeekView.IEventLongPressListener, MonthLoader.IMonthChangeListener
            {
                private SupportToolbar mToolbar;

                private static int TYPE_DAY_VIEW = 1;
                private static int TYPE_THREE_DAY_VIEW = 2;
                private static int TYPE_WEEK_VIEW = 3;
                private int mWeekViewType = TYPE_THREE_DAY_VIEW;
                private WeekView mWeekView;
                protected override void OnCreate(Bundle bundle)
                {
                    base.OnCreate(bundle);

                    // Set our view from the "main" layout resource
                    SetContentView(Resource.Layout.EventView);
                    ---
                ----------  
                    ---
                ---------- 
                    ---
                ---------- 

                 }
          }

If I am using StartActivity my event page is showing as separate page and if I use SetNativeControl(_view) my events are not showing in Content page.
Please help me for how to load events activity with in Content page by using ViewRenderer.

Thanks.

Problem with CustomFont in Xamarin.Forms(doesn't work on iOS)

$
0
0

Hi, I've tried to use three different fonts on Xamarin.Forms and on Android works fine, but on iOS it doesn't work...

I followed this example: https://developer.xamarin.com/guides/xamarin-forms/user-interface/text/fonts/
1. I added my files in Resources - > Font
2. I edited Info.plist file and now i have:

3. I'm trying to use like this:
<Label.FontFamily>
<OnPlatform x:TypeArguments="x:String">
<On Platform="iOS" Value="Black" />
<On Platform="Android" Value="Black.ttf#Black" />
</OnPlatform>
</Label.FontFamily>

In Archive.zip you have what I want to use.

Where is the problem?

AppCompatActivity in xamarin.Android ViewRenderer

$
0
0

Hi,
I am working on calendar events in my xamarin forms android app by using Com.Alamkanak.Weekview. I want to load calendar events in Content page. My code in Content page like

    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:controls="clr-namespace:App.CustomControls"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:local="clr-namespace:app.CustomControls">
        <ContentPage.Content>
                 <StackLayout Orientation="Vertical">
                    <ContentView>
                        <OnPlatform x:TypeArguments="View">
                            <OnPlatform.Android>
                                <local:CustomCalendarEvent/>
                            </OnPlatform.Android>
                        </OnPlatform>
                    </ContentView>
                </StackLayout>
              </ContentPage.Content>
    </ContentPage>

my CustomCalendarEvent is

public class CustomCalendarEvent : View{ }

my ViewRenderer is like

    [assembly: ExportRenderer(typeof(CustomCalendarEvent), typeof(CustomCalendarEventRenderer))]
    namespace App.Droid.CustomRenderers
    {
        public class CustomCalendarEventRenderer : ViewRenderer
        {
            protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
            {
                base.OnElementChanged(e);
                if (Control == null)
                {
                    try
                    {
                        var intent = new Intent(Forms.Context, typeof(Events));
                        Forms.Context.StartActivity(intent);

                        //var context = Xamarin.Forms.Forms.Context;
                        //LayoutInflater inflater = context.GetSystemService(Context.LayoutInflaterService) as LayoutInflater;
                        //var _view = inflater.Inflate(Resource.Layout.EventView, this, false);
                        //mWeekView = _view.FindViewById<WeekView>(Resource.Id.weekView);
                        //SetNativeControl(_view);
                    }
                    catch (Exception ex)
                    {
                        string Message = ex.Message;
                    }
                }    
            }
        }
    }

and my Events activity is like

        public class Events : AppCompatActivity, WeekView.IEventClickListener, WeekView.IEventLongPressListener, MonthLoader.IMonthChangeListener
            {
                private SupportToolbar mToolbar;

                private static int TYPE_DAY_VIEW = 1;
                private static int TYPE_THREE_DAY_VIEW = 2;
                private static int TYPE_WEEK_VIEW = 3;
                private int mWeekViewType = TYPE_THREE_DAY_VIEW;
                private WeekView mWeekView;
                protected override void OnCreate(Bundle bundle)
                {
                    base.OnCreate(bundle);

                    // Set our view from the "main" layout resource
                    SetContentView(Resource.Layout.EventView);
                    ---
                ----------  
                    ---
                ---------- 
                    ---
                ---------- 

                 }
          }

If I am using StartActivity my event page is showing as separate page and if I use SetNativeControl(_view) my events are not showing in Content page.
Please help me for how to load events activity with in Content page by using ViewRenderer.

Thanks.

How to change "Back button" to "Menu" on MasterDetailPage? [Android]

$
0
0

Hi there! I'm facing the following issue:

I have a drawer menu (implemented with MasterDetailPage) with 3 items. When you first run the app you see an hamburger menu icon on top left.
When you click in one of these items, the page loads with an back arrow.
I'm trying to accomplish that these three pages must still have the hamburger menu item on its Action Bar. And the navigation after those, loads with the back button.

I ended up thinking that the Icon property for MasterPage won't work for Android.

I made it work on iOS but nothing I do seems to work on Android.

My code:

MainPage.cs
public class MainPage : MasterDetailPage { protected override void OnAppearing() { base.OnAppearing(); this.GetMenuPage().ListView.ItemSelected += OnItemSelected; } private void OnItemSelected(object sender, SelectedItemChangedEventArgs e) { var item = e.SelectedItem as Menu; if (item == null) return; // this.GetNavigationPage().PushAsync((Page)Activator.CreateInstance(item.Pagina)); ((NavigationPage)this.Detail).PushAsync((Page)Activator.CreateInstance(item.Pagina)); this.GetMenuPage().ListView.SelectedItem = null; IsPresented = false; } }

MenuPage.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" x:Class="BNB.CapturaGeodesica.MenuPage" Padding="0,40,0,0" BackgroundColor ="#A5183C" Title="Menu " Icon="ic_hamburguer_menu"> <!-- ## This works on iOS. But on Android, it won't show up. ##-->

DetailPage1.cs
public DetailPage1() { NavigationPage.SetHasBackButton(this, false); // Here I get rid of the back button. But I can't manage to show the menu icon on Android. InitializeComponent(); }

I'm attaching the result on iOS and Android. Just to clarify, to reach "Second page" on iOS or Android, assume that I opened the drawer menu and selected "Second page".

OBS: I need to have the page history.

Thank you for any help!

  • this is my first post, if I messed it up, sorry -

Xamarin form : Unable to recieve notification in IOS xamarin form

$
0
0

I have developed app for ios and android in xamarin form cross platform. The problem i am facing in notification that i can recive notification in android and its working absolutely fine, even i can open specific page from notification data, but in IOS i am not able to recieve notification. Here is my code from where i am sending notification

   public async void NewTaskNotification(string user_token, string titlee, string bodyy, string openpage, long? mrno, DateTime? appointmentdate)
    {
        i++;
        WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
        tRequest.Method = "post";
        tRequest.ContentType = "application/json";
        var objNotification = new
        {
            to = user_token,
            data = new
            {
                title = titlee,
                body = bodyy,
                priority = "high",
                id = i,
                icon = "ic_stat_ic_stat_ic_notification",
                color = "#2F3C51",
                Background = "#2F3C51",
                open_page = openpage,
                mr_no = mrno,
                appointmentDate = appointmentdate,
            },
        };
        string jsonNotificationFormat = Newtonsoft.Json.JsonConvert.SerializeObject(objNotification);
        Byte[] byteArray = Encoding.UTF8.GetBytes(jsonNotificationFormat);
        tRequest.Headers.Add(string.Format("Authorization: key={0}", "AAAAoQ445fk:APA91bHagr12v6bGUqE2d8soHCMXwo4rD6wyM_LFp6yD9b968J3SQQ9u8T5rsFBtsPzL-ct_cCjad_YPpEjaw5tq_OqR_asB5-zgKqyQfhV2djFxAAbK7PBPCZHMI2Y6KmNN8R-MItOA"));
        tRequest.Headers.Add(string.Format("Sender: id={0}", "691728344569"));
        tRequest.ContentLength = byteArray.Length;
        tRequest.ContentType = "application/json";
        using (Stream dataStream = tRequest.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);
            using (WebResponse tResponse = tRequest.GetResponse())
            {
                using (Stream dataStreamResponse = tResponse.GetResponseStream())
                {
                    using (StreamReader tReader = new StreamReader(dataStreamResponse))
                    {
                        String responseFromFirebaseServer = tReader.ReadToEnd();
                        FCMResponse response = Newtonsoft.Json.JsonConvert.DeserializeObject<FCMResponse>(responseFromFirebaseServer);
                        if (response.success == 1)
                        {
                            Console.WriteLine("succeeded");
                        }
                        else if (response.failure == 1)
                        {
                            Console.WriteLine("failed");

                        }
                    }
                }
            }
        }
    }

with this code i am able to recieve notification and even open specific page but only with android, its not working with ios, but when i try to send notification to IOS from firebase console, its working fine.

Here is my appdelegate.cs

public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {

        public override bool FinishedLaunching(UIApplication uiApplication, NSDictionary launchOptions)
        {
            Rg.Plugins.Popup.Popup.Init();
            CachedImageRenderer.Init();
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());
            FirebasePushNotificationManager.Initialize(launchOptions, true);
            FirebasePushNotificationManager.CurrentNotificationPresentationOption = UNNotificationPresentationOptions.Alert | UNNotificationPresentationOptions.Badge;
            UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate();
            return base.FinishedLaunching(uiApplication, launchOptions);
        }
        public class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate
        {
            public UserNotificationCenterDelegate()
            {
            }

            public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
            {
                // Do something with the notification
                Console.WriteLine("Active Notification: {0}", notification);

                // Tell system to display the notification anyway or use
                // `None` to say we have handled the display locally.
                completionHandler(UNNotificationPresentationOptions.Alert);
            }
        }
        public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            FirebasePushNotificationManager.DidRegisterRemoteNotifications(deviceToken);
        }

        public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
        {
            FirebasePushNotificationManager.RemoteNotificationRegistrationFailed(error);

        }

        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
        {

            FirebasePushNotificationManager.DidReceiveMessage(userInfo);
            // Do your magic to handle the notification data
            System.Console.WriteLine(userInfo);

            completionHandler(UIBackgroundFetchResult.NewData);
        }
    }

need to know where i am doing wrong for IOS

Does not get response from REST API in Xamarin forms application

$
0
0

Hello All,

I am beginner in Xamarin and trying to consume REST API in Xamarin forms to display the data using ListView in tab page. Below is the Xamarin version in my development environment:

Xamarin - 4.12.3.78
Xamarin.Android.SDK - 9.1.5.0
VS 2017 - Community (15.9.5)

The problem is,

For Android, let's say if we run the application 10 times, it gets the response from REST API 5-6 times only. In other case, the application gets stuck at 'HttpResponseMessage response = await client.GetAsync(subUrl)'.

I don't understand what is the error? Is there any way we can see the log for this error?

Also, even for UWP, the application is throwing an error "Access Denied".

I have attached the screenshots of the Xaml and Xaml.cs file for the reference.

Can anyone please help me on this?

How to get a reference from the listview using DataTemplate?

$
0
0

I have a basic ListView that uses a DataTemplateSelector

<ListView **x:Name="listView"** ItemsSource="{Binding PostDb}"
                  ItemSelected="ListView_OnItemSelected"
                  ItemTemplate="{StaticResource ActivityDataTemplateSelector}"
                  HasUnevenRows="True"
                  IsPullToRefreshEnabled="true" Refreshing="ListView_OnRefreshing"
                  SeparatorVisibility="Default"
                  SeparatorColor="Gray" />

But I have simply no idea how to retrieve listview's reference inside my DataTemplates.

<Image Source="Test.png">
                <Image.GestureRecognizers>
                    <TapGestureRecognizer 
                                        NumberOfTapsRequired="1"
                                        BindingContext="**{Binding Source={x:Reference listView}**, Path=BindingContext}"
                                        Command="{Binding CommentButton}"
                                        CommandParameter="{Binding Source={x:Reference LayoutButtons}, Path=BindingContext}" 
                                    />
                </Image.GestureRecognizers>
            </Image>

Any guess?


Command Binding From Xaml to ViewModel does not work (not debugable)

$
0
0

Hi.

I have a XAML form with button.

 <StackLayout.BindingContext>
                <viewModels:CartVM/>
            </StackLayout.BindingContext>
            <!-- other code -->

         <ListViewItemsSource="{Binding Items}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>

                        Button Text=" - "
                              Command="{Binding DecreaseQtyCommand}"
                              CommandParameter="{Binding}"
                        />
          <!-- other code -->

This is the ViewModel:

 public class CartVM : BaseViewModel
    {
        public CartVM()
        {
            Items.CollectionChanged += ItemsHasBeenChanged;
        }

       public ObservableCollection<ShopCart> Items
        {
            get
            {
                return // list
            }
        }

       public string Title {get;set;}
       public string TotalAmount{get;set;}

       public ICommand DecreaseQtyCommand
        {
            get
            {
                return new Command<ShopCart>((ShopCart shopCart) =>
                { 
                    shopCart.Qty -= 1;
                    OnPropertyChanged("Items");
                });
            }
        }

The prolbem only with the Commands, the other Properties of CartVM work via Binding on the Xaml, like CartVM.Title, CartVM.TotalAmount

Data transfer from dynamic page?

$
0
0

I have a dynamic ContentPage

Code

Marked red area = Content this page

Output =

Marked red area = this entry text will always be changeable. When click this Entry openable a Page and User select new Entry Text value. Look picture

Data transfer codes =

Entry value change code

My problem is =
When click entry open page select new value
I get the value of the line I clicked

but Entry text doesnt Update

Button render doesn't receive gesture events (andorid)

$
0
0

I want to know when a button is pressed and when a button is released. I seen this example where the gestures are captured for a label here:

http://arteksoftware.com/gesture-recognizers-with-xamarin-forms/

The example works great. I tried the same for a Button but the event handlers are never fired. Any ideas why? Below is the button render;

` using Xamarin.Forms.Platform.Android;
using Xamarin.Forms;
using XamarinFormsGestureRecognizers;
using XamarinFormsGestureRecognizers.Droid;
using Android.Views;

[assembly: ExportRenderer (typeof (OnTouchButton), typeof (OnTouchButtonRenderer))]


namespace XamarinFormsGestureRecognizers.Droid
{
    public class OnTouchButtonRenderer : ButtonRenderer
    {
        private readonly FancyGestureListener _listener;
        private readonly GestureDetector _detector;

        public OnTouchButtonRenderer()
        {
            _listener = new FancyGestureListener ();
            _detector = new GestureDetector (_listener);
        }

        protected override void OnElementChanged (ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged (e);

            if (e.NewElement == null)
            {
                this.GenericMotion -= HandleGenericMotion;
                this.Touch -= HandleTouch;
            }

            if (e.OldElement == null) {
                this.GenericMotion += HandleGenericMotion;
                this.Touch += HandleTouch;
            }
        }

        void HandleTouch (object sender, TouchEventArgs e)
        {
            System.Diagnostics.Debug.Write("Button push");
            _detector.OnTouchEvent (e.Event);
        }

        void HandleGenericMotion (object sender, GenericMotionEventArgs e)
        {
            System.Diagnostics.Debug.Write("Button motion");
            _detector.OnTouchEvent (e.Event);
        }

    }
}

`

How to delete files using xamarin forms

$
0
0

I tried to delete file from specific directory(Folder) but it doesn't work for me

I used this sample but doesn't work

https://forums.xamarin.com/discussion/123031/deleting-the-media-file-from-storage

this is my code

  DeletePhoto.Clicked += async (sender, args) =>
            {
                var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
                {
                    PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,

                });


                if ( file != null)
                {
                    if (File.Exists(file.Path))
                    {
                        DependencyService.Get<IFileManager>().DeleteFile(file.Path);
                    }
                    file.Dispose();

                }
            };

In android

        public class FileManager : IFileManager
            {
                public void DeleteFile(string source)
                {
                    File.Delete(source);
                }
            }

In mainfest permisson is given but something didn't happen and i find the file which i deleted

Xamarin Forms - FontAwesome works iOS,Android but UWP display [x]

$
0
0

Hello dear Xamariners !

I'm wasting a lot of time trying to figure out why FontAwesome doesn't work on Android & iOS.
No need to tell you that I've tried several solutions I found on this forum.

To help you to help me (what ? haha)
Here are some screenshots :

On iOS :

On UWP or Android (kind of same result I don't have the right icon)

The FontFamily resource in app.xaml :

My Fonts folder :

My VS fonts Android folder with the properties AndroidAsset // copy if newer

My VS fonts UWP folder with the properties Content // Do not copy

Do you have any idea why it isn't working ?

I've tried several way to declare my font (without the otf.#name of font , with .otf#name of font style , with .otf only)

If anybody got this working, it would be awesome :) to get some help.
PS : I'd like to avoid a custom renderer

I wish you all a good weekend !

Viewing all 89864 articles
Browse latest View live


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