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

ListView behaviour in UWP project

$
0
0

I've just started working with Xamarin Forms and I'm trying to wrap my head around a couple of things that are (not) happening relating to a bound ListView, hopefully someone can shed some light on this for me.

    private Item _SelectedItem;        
    public Item SelectedItem;
    {
       get => _SelectedItem;
       set
       {
          _SelectedItem; = value;
          NotifyPropertyChanged("SelectedItem");
        }
    }

    public ObservableCollection<Item> ItemsList { get; set; }
    public ICommand RemoveItemCommand { get; private set; }


    public MyViewModel()
    {
       RemoveItemCommand = new Command(RemoveItem, CanRemoveItem);
    }

    private void RemoveItem()
    {
       ItemsList.Remove(SelectedItem);
    }

    private bool CanRemoveItem()
    {            
       return SelectedItem != null;
       //return true;
    }

And the Xaml:

  1. When a row is selected there is no visual indication that it has been selected (ie. row is not highlighted)

  2. When a row is selected, the SelectedItem property in my ViewModel contains the selected correct object, but the
    CanRemoveItem property of the command is never set to true so the button is always disabled. However, RemoveItem method and button work when CanRemoveItem is manually set to true.

Is this expected behaviour or am I missing the mark somewhere?


How can i conect

$
0
0

I have an application, which I want that from any phone that has it, can connect to a remote database and be able to consume it

Setting Cookies in a WebView

$
0
0

I received a request this morning to share how I set cookies in a webview so here it is, hope it's helpful. It's worked for me so far but feel free to comment on it if it can be improved.
First, you have to create a custom render for your webview in iOS and Android, there are many examples of how to do that so I won't go into that here.
In my shared code I have a UserInfo object that contains a CookieContainer:

    public class UserInfo
    {
        public static CookieContainer CookieContainer = new CookieContainer();
    }

In my (native) login page I have an event called OnLoginClickAsync which validates the login information. I create a HTTPClientHandler:

                var handler =  new HttpClientHandler {CookieContainer = UserInfo.CookieContainer};
                var httpClient = new HttpClient(handler);

Then save the resulting CookieContainer if the validation is successful:

                UserInfo.CookieContainer = handler.CookieContainer;

On the Android side in the OnElementChanged event for my web view renderer I use:

            var cookieManager = CookieManager.Instance;
            cookieManager.SetAcceptCookie(true);
            cookieManager.RemoveAllCookie();
            var cookies = UserInfo.CookieContainer.GetCookies(new System.Uri(AppInfo.URL_BASE));
            for (var i = 0; i < cookies.Count; i++)
            {
                string cookieValue = cookies[i].Value;
                string cookieDomain = cookies[i].Domain;
                string cookieName = cookies[i].Name;
                cookieManager.SetCookie(cookieDomain, cookieName + "=" + cookieValue);
            }

On the iOS side in the OnElementChanged event for my web view renderer I use:

            // Set cookies here
            var cookieUrl = new Uri(AppInfo.URL_BASE);
            var cookieJar = NSHttpCookieStorage.SharedStorage;
            cookieJar.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
            foreach (var aCookie in cookieJar.Cookies)
            {
                cookieJar.DeleteCookie(aCookie);
            }

            var jCookies = UserInfo.CookieContainer.GetCookies(cookieUrl);
            IList<NSHttpCookie> eCookies = 
                (from object jCookie in jCookies 
                 where jCookie != null 
                 select (Cookie) jCookie 
                 into netCookie select new NSHttpCookie(netCookie)).ToList();
            cookieJar.SetCookies(eCookies.ToArray(), cookieUrl, cookieUrl);

Also, if you want to use the cookie container in a straight call - not in a webview - just set it in the handler:

            var handler = new HttpClientHandler { CookieContainer = cookieContainer };
            var httpClient = new HttpClient(handler);

Xamarin.iOS app to Xamarin Forms?

$
0
0

I am planning to re-write my Xamarin.iOS native app to Xamarin Forms. Is there any specific procedure available I could follow up or any references?

And if anyone has done this, can you pls brief it how you achieved?

Thanks.

Need a radio button to select an address in a collection view..

$
0
0

Hello all,
Actually I am working on an e-commerce application. And need a radio button to select the address from multiple address. and the selected address will go forward. And in this image, only one address is showing..and the other address will continue in vertical orientation..

Is it possible to change binding behavior for Entry.Text

$
0
0

When I bind a view model property to Entry.Text the property is updated every time something changes in the Entry, literally after each button press. Maybe it is desired behavior for most but in my case a better behavior would be to update the view model property only after Entry loses the input focus. Is it possible to change the behavior to what I need? I assume I can figure out how to implement what I need in other way but first I would like to make sure that I didn't miss anything.

Access denied at saving file in uwp

$
0
0

I tried to save a file in uwp, but the access denied.

                String fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Record", "record.opml");
                String dirName = Path.GetDirectoryName(fileName);

                if (!Directory.Exists(dirName))
                    Directory.CreateDirectory(dirName);

                if (!File.Exists(fileName))
                    File.Create(fileName);

                using (var streamWriter = new StreamWriter(fileName, true))
                {
                    streamWriter.WriteLine(doc);
                }

Options to Properly Add FireBase to My Xamarin Forms Project

$
0
0

Hi guys,

I need to use firebase Cloud Messaging in my project, decide to follow all the official microsoft guidelines but I have had some bugs trying to add dependencies.

First, when adding the json file generated by Firebase (google-services.json) in the Android project, I don't see the option to add the resource as **GoogleServiceJson **(Step: In Properties> Advanced> Build Action, select GoogleServicesJson.)

Second, when I try to add the NuGetPackage Xamarin.Firebase.Messaging in the android project it throws me the error the $ (TargetFrameworkVersion) for PGTApp.Android (v8.1) is less than the minimum required $ (TargetFrameworkVersion) for Xamarin.Forms ( 9.0).
I am clear where I have to change for this to be fixed, but it remains the same without being able to be added.

Finally, I have updated to the latest version of xamarin forms but still unable to enable Firebase in my project.

Some aspects of my project:
1. Xamarin Forms version: 4.6.0.800
2. .Net Standard version: 2.0
3. Xamarin.Firebase.Messaging version: 17.1740.1 (not installed)
4. Sdk version minimum Api16 and maximum Api29. For the Android project.

My main question is what other options can I have to use Firebase in my project or how can I solve this problem?

Thank you very much, Greetings from Panama


HttpClient very slow

$
0
0

Hello,

I develop an application that displays a MotionJPEG stream.
It was working great until I had a bug on iOS that froze the app when the connexion is lost (code stuck at Stream.ReadAsync and never returns).

So I changed all my streaming code from the old WebRequest - HttpWebRequest - GetRequestStream to the new and recommanded native HttpClient - SendAsync - ReadAsStreamAsync (using AndroidClient and NSUrlSession).

With that change the bug was fixed : great !
But since the streaming is very, very slow...

After some digging, I found that in release on Android it is still ok, but in Debug mode on Android AND on iOS (Debug and Release), it is very very slow.
It looks like the code is running fast (as usual), but the app has too few to read from the stream (like a bad slow internet connexion).

I've tried several things without success...
Do you have any ideas please ?

Thanks.
Nicolas.

How does one create a button or label with underlined text?

$
0
0

I feel stupid even asking, but there you go. It isn't obvious to me. I don't see a way to underline or add/set other text type attributes to text.

Issue with Plugin.BLE do not scan devices

$
0
0

Hi!

I'm facing a issue trying to connect to a Bluetooth LE device.

I downloaded the Plugin.BLE and I used the sample included without any problem, I connect and read/write data.

Now, I try to deploy on my App, I follow the instructions on the github repository, add permissions to AndroidManifest.xml. , but when I execute adapter.StartScanningForDevicesAsync(), nothing happens, I don't get the list of devices. There are several devices all around and also the one I want to connect to.

This is my code

public partial class PageSettingsDevice : ContentPage
{
IBluetoothLE ble;
IAdapter adapter;
ObservableCollection deviceList;
IDevice device;
private CancellationTokenSource _cancellationTokenSource;

    public PageSettingsDevice()
    {
        InitializeComponent();

        ble = CrossBluetoothLE.Current;
        adapter = CrossBluetoothLE.Current.Adapter;
        deviceList = new ObservableCollection<IDevice>();

        //adapter.DeviceDiscovered += _bleAdapterDeviceDiscovered;
    }

    private bool status()
    {
        var state = ble.State;

        DisplayAlert("Notice", state.ToString(), "OK !");
        if (state == BluetoothState.Off)
        {
            DisplayAlert("Atención", "Your Bluetooth is off ! Turn it on !", "Aceptar");
        }

        if (ble.State == BluetoothState.Off || ble.State == BluetoothState.TurningOff || ble.State == BluetoothState.Unauthorized || ble.State == BluetoothState.Unknown)
            return false;
        else
            return true;
    }

    async void OnDiscoverDeviceBlueToothClicked(object sender, EventArgs e)
    {
        try
        {
            if (status())
            {
                adapter.DeviceDiscovered += (s, a) =>
                {
                    if (device.Name.Contains("Coltech"))
                            adapter.ConnectToDeviceAsync(device);
                };

                //We have to test if the device is scanning 
                if (!ble.Adapter.IsScanning)
                {
                    _cancellationTokenSource = new CancellationTokenSource();

                    adapter.ScanMode = ScanMode.LowLatency;
                    await adapter.StartScanningForDevicesAsync(null,null,false,_cancellationTokenSource.Token);

                    var list = adapter.ConnectedDevices;
                }
            }                
        }
        catch (Exception ex)
        {
            DisplayAlert("Notice", ex.Message.ToString(), "Error !");
        }
    }

    async void _bleAdapterDeviceDiscovered(object sender, DeviceEventArgs e)
    {
        if (device != null)
        {
            if (device.Name.Contains("Coltech"))
                await adapter.ConnectToDeviceAsync(device);
        }
    }
}

Any help is wellcomed, thanks

Xamarin Forms app restarts instead of resume on iOS app switching.

$
0
0

Hello

Have a Xamarin Forms app on iOS.

When testing on physical device (iPhone), when the app is switched to background and then to foreground, it restarts.

Expected behaviour is to resume from where it left off.

Works fine on simulator.

Pl advise asap.

Thanks

How to retain Menu in Master Detail Page navigation

$
0
0

Seems I am running into the same issue with the Master Detail page as I did the Shell. I can't seem to figure out how to retain the hamburger menu while navigating. As long as I am navigating from the first Master Detail page, I can keep the hamburger menu. But as soon as I navigate from a page that is loaded into the details pane, the menu goes away.

For instance

MDPage
-First Level Detail Page (has Menu)
--Second Level Navigated from First Level (No Menu)

I am navigating using Navigation.PushAsync(new Page). The Navigation page is already the details page, so you'd think that this would cause the details page to update, but instead its replacing the entire view.

I tried creating static references in the App for the Master and Detail page, but this wont allow any navigation at all for some reason.

Shell - Page with complex constructor

$
0
0

I have a page with complex constructor

public partial class SocialLoginPage : ContentPage
    {
        public SocialLoginPage(IOAuth2Service oAuth2Service)
        {
    ...
    }

I would like to add it to flyoutitem in shell

<FlyoutItem Route="home" Title="Home" Icon="ic_ig.png">
        <ShellContent ContentTemplate="{DataTemplate pages:SocialLoginPage}"/>
    </FlyoutItem>

But I am getting error that default constructir is missing for page.
How to resolve this issue?

Thanx,
D

Using existing sqlite database

$
0
0

Hi, I have an app which is similar to a dictionary app and hence has a pre-built sqlite database file.
When app is opened for the first time, I copy that file from android assets to Personal directory so that app can access it easily.
The problem is, file is pretty big, around 200 mb. After copying I have 2 db files, one in personal folder which app uses and one in assets.
App size becomes 400 mb. Is there any way to
1. Delete assets file after copy or
2. Move file instead of copying or
3. App access db file from assets and not copy it to personal folder


How to restore the navigation stack after page suspend / resume in Xamarin.Forms

$
0
0

Hey Guys,

I'm just getting used to Xamarin.Forms and cant seem to find a standard way of restoring the navigation stack after a suspend / restore (like when the device gets rotated).

Using either the v1.3.0 release or maybe even xamarin.forms.labs I can capture some restore/suspend events, but I dont understand how I'm meant to restore the navigation stack in my app?

For example, if I have my HomeView and HomeViewModel, which has a list view of items. Somebody clicks the list view item and it navigates to my ItemView and ItemViewModel. Then the user rotates the screen - how do I restore them to where they just were?

Can anyone point me in the right direction?

Thanks

Matt

Forms app loses all state and boots from scratch when switching between apps

$
0
0

My Android Forms app will start from zero each time I switch to another app and then switch back.

I already have the "ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation" fix applied but this only solves the issue for screen rotations. User task switching still results in all state being lost.

Improved life cycle support

$
0
0

Summary

As one of the authors of ReactiveUI, I have found that Xamarin.Forms does not provide the requisite view life cycle hooks to enable the framework to manage the activation and deactivation of resources in response to the comings and goings of views.

Specifically, I have found these problems:

  • Page.Appearing actually fires in response to ViewDidAppear on iOS. One of ReactiveUI's benefits is its code-based, type-safe binding infrastructure. Appearing is the only hook we can use to get stuff on the screen, but it fires too late on iOS, so there is a brief period where the screen is not populated with data. I have already attempted to start a discussion here, but it seemed to stagnate.
  • Given a View, there is no way to tell when that View appears and disappears from the screen. There is no View.Appearing or View.Disappearing events as there is for Page. It might seem appropriate to therefore search up the visual tree for the Page and hook into that. However, this is inefficient (but perhaps that's inevitable) and there is no means of knowing when the Page itself changes. There is no PageChanged event, and PropertyChanged does not fire in response to the Page changing.

API Changes

  • Page.Appearing should fire in response to ViewWillAppear on iOS. Moreover, there should be Page.Appeared and Page.Disappeared counterparts. Yes, this is potentially breaking to people who are hooked into Appearing and rely on it firing in response to ViewDidAppear on iOS. However, that behavior has always been incorrect and the fix for these people is literally to change Appearing to Appeared (or hold off on the XF upgrade).
  • Ideally, add Appearing, Appeared, Disappearing, Disappeared to View and have them Just Work. Failing that, ensure there is a hook by which framework authors can know the hosting Page for a View has changed. Perhaps a specific PageChanged event, or just ensuring PropertyChanged works as expected in this scenario.

Intended Use Case

The use case here is to give framework authors what they need to facilitate the creation of self-sufficient, standalone, encapsulated components by framework consumers. I specifically work on ReactiveUI, but other framework authors will/have run into the same issues.

ModEdit - Spec incoming ASAP

not show image https

$
0
0

<Image Source="https://cdn.vatanbgs.com/Content/Images/Products/460_466/637089327869489423.jpg" 
       WidthRequest="150" HeightRequest="150"></Image>![](https://us.v-cdn.net/5019960/uploads/editor/1v/n06i7lpljpih.png "")

Why doesn't it open on Android 5?

log eeror

CachingStrategy Cannot Use in Listview Rendender

$
0
0

CachingStrategy Cannot Use in Listview Rendender.

public class NoBounceListView : ListView
{
}

[assembly: ExportRenderer(typeof(NoBounceListView), typeof(NoBounceListViewRenderer))]
namespace TestProject.Droid.Renderer
{
public class NoBounceListViewRenderer : ListViewRenderer
{
public ListViewCachingStrategy CachingStrategy { get; private set; }
protected override void OnElementChanged(ElementChangedEventArgs e)
{
base.OnElementChanged(e);

        if (Control != null)
        {
            CachingStrategy = ListViewCachingStrategy.RecycleElementAndDataTemplate;
        }
    }
}

[assembly: ExportRenderer(typeof(NoBounceListView), typeof(NoBounceListViewRenderer))]
namespace TestProject.iOS.Renderer
{
public class NoBounceListViewRenderer: ListViewRenderer
{
public ListViewCachingStrategy CachingStrategy { get; private set; }
protected override void OnElementChanged(ElementChangedEventArgs e)
{
base.OnElementChanged(e);

        if (Control != null)
        {
            Control.Bounces = false;
            CachingStrategy = ListViewCachingStrategy.RecycleElementAndDataTemplate;
        }            
    }
}
Viewing all 89864 articles
Browse latest View live


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