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

How to transform pixel designs into xamarin forms designs

$
0
0

Assume I get following dimensions from designer for heights(please put image url in your browser, i can't post images yet):
us.v-cdn.net/5019960/uploads/editor/h4/o9mqxh290isb.png

How do I transform these pixel sizes to Xamarin forms DUI(device-independent units)? Are there any designer tools to help with this?


Program logic question

$
0
0
Hello,

I am in the process of porting my app from UWP to Xamarin Forms. I have an app that connects to a server to download data, then shows this data (several individual items) to the user and allows the user to also manipulate an item and as such send data to the server.

In have three relevant model classes:
1. Settings: stores server and authentification properties.
2. MainModel: Contains the settings class an handles downloading data from the server to create several ItemModels
3. ItemModel: Parses the data from the server and is consumed by a viewModel to show the data.

Now I want to able to send data back to the server. In my old UWP app I called something like App.SendToServer(string parameter) from each ItemModel.

Is this good practice? When porting my app to Xamarin I made sure to allow all instances of the classes to be working in any environment. I thought about having each ItemModel itself being able to send to the server, but therefore they must all contain a settings class and this seems bad to me because of performance and because multiple commands could be sent to the server at the same time (I would prefer to work through them one by one and await the result).

What are my options? Singleton/static class? Only passing a reference to each ItemModel? Keeping the function in App.cs?

How to set internal Property "IsFocused" of VisualElement outside of xamarin API

$
0
0

Hi there,

I'm using a custom Entry, which then uses my native iOS cutom UITextField. I wanna hook up the custom UITextField's EditingDidBegin/End to custom Entry's IsFocused just like the following code:

// following code is in CustomRenderer : ViewRenderer<CustomEntry, CustomUITextField>
myCustomUITextField.EditingDidBegin += delegate (object sender, EventArgs args) {
    myCustomEntry.IsFocused = true; // Error in this line: can't set IsFocused property outside of xamarin API
};

My problem is Entry.IsFocused is internal, could anyone tells me how to set Entry.IsFocused property outside of xamarin API?

Thank you.

Can we call background service of android from Xamarin.Forms ?

$
0
0

I've written a background service in android. Can it be called from Xamarin forms ? And do we need dependency service for that ?
Please help.
Thanks in advance :smile:

Toolbar Items break when using a ControlTemplate?

$
0
0

I've been stuck for hours now so any handy hints would be very welcome!

I am using mvvm with a controltemplate and the page works fine with all commands.

I have attempted to add a settings icon to the navigation bar. It appears correctly and pressing the icon visibly changes, but it fails to trigger the command. If I remove the control template, the command works fine.

I've minimised my template down to just a stack layout:
<ControlTemplate x:Key="MainPageTemplate"><br /> <StackLayout VerticalOptions="FillAndExpand"><br /> <ContentPresenter VerticalOptions="FillAndExpand" /><br /> </StackLayout><br /> </ControlTemplate><br />

Here is the toolbaritem that is rendered fine
&lt;ContentPage.ToolbarItems><br /> <ToolbarItem Name="Settings" Order="Primary" Priority="0" Icon="settingsIcon.png" Command="{Binding SettingsCommand}" /><br /> &lt;/ContentPage.ToolbarItems><br />

My problem looks exactly the same as the comment in here by @BenoitRocco:
https://forums.xamarin.com/discussion/17880/toolbaritem-command-binding-doesnt-work

So ive tried adding a source but no joy:
Command="{Binding BindingContext.SettingsCommand, Source={x:Reference MainMenuView}}" />

I must be missing something obvious?
Can i definitely use a template on the whole page with toolbar items?

Thanks,
Andy

AlertDialog in scanning mode (ZXing.Mobile bar code scanner)

$
0
0

Please, help!
AlertDialog is displayed in MainActivity.
How to draw a conclusion in barCodeLayout?

My code:
public void TestLV_ItemClick(object sender, ItemClickEventArgs e)
{
var scanner = new MobileBarcodeScanner();
var opt = new MobileBarcodeScanningOptions
{
DelayBetweenContinuousScans = 3000
};
scanner.UseCustomOverlay = true;
var barCodeLayout = LayoutInflater.FromContext(this).Inflate(Resource.Layout.BarCodeLayout, null);
scanner.CustomOverlay = barCodeLayout;
Button enter = scanner.CustomOverlay.FindViewById<Button>(Resource.Id.btnIn);
enter.SetBackgroundColor(Color.SeaGreen);
enter.Click += delegate (Object o, EventArgs ex) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Scanning Mode");
alert.SetMessage("Go to INPUT scan mode?");
alert.SetPositiveButton("Yes", (senderAlert, args) => {
Toast.MakeText(this, "Scanning of INPUTS", ToastLength.Short).Show();
InOut = "Input";
(o as Button).SetBackgroundColor(Color.SeaGreen);
});
Dialog dialog = alert.Create();
dialog.Show();
};
scanner.ScanContinuously(opt, HandleScanResult);
}

P.S.
Sorry for my English.

How can i do to remove the title bar?

$
0
0

I have a App and when i run my App appear a blue bar on the top of my App. Is there how to remove that bar?

Easy way to hide title bar

$
0
0

Hi everyone,

Does it has a simple way with Xamarin.Forms to hide the title bar in an Android (or iOS or Windows Phone) Application?

This line doesn't work for me :

NavigationPage.SetHasNavigationBar(this, false);

Thanks in advance.


while building my xamarin.ios project it is showing object reference not set to an instance

$
0
0

while building my xamarin.ios project it is showing error object reference not set to an instance of an object..

TabbedPage - OnAppearing called twice in android

$
0
0

Hello,

We have a TabbedPage layout and our app makes the web service call in the OnAppearing of the tab page. The OnAppearing event is called properly in iOS but in Android we are observing that the OnAppearing gets called twice. Due to this behaviour we are having problem making proper endpoint call in the onAppearing for android.

I can see that this is an issue reported in BugZilla but I dont see any proper resolution on the issue. https://bugzilla.xamarin.com/show_bug.cgi?id=44211

This is really annoying as one way or other we are dependent on the onAppearing method. We tried to add some local variables to make sure the function gets called only once like so.

constructor()
{
.....
 called = false;
}

protected override void OnAppearing()
{
    if(!called){
        ....
        called = true;
    }
}

With this method onAppearing does not get triggered after the first time. ( Not getting called on further change of tabs )

Is there any better way to do this? Also any update on the issue would also be helpful.

A WebView or Image control which zooms

$
0
0

I need a control which allows the user to Pinch and zoom using xamarin.forms.

I need to display an image in the control and allow the user to zoom it.

Currently I am using WebView to display my image in the app but I am not able to zoom from my device.

Custom circular slider control in xamarin forms

$
0
0

Is it possible to create custom slider control like this in xamarin forms?

DependencyService interface implementation instantiation (singleton)

$
0
0

Hi

I have some Bluetooth Low Energy (BLE) code in a Xamarin.Android and Xamarin.iOS project. This performs all the work in my app, running as a Service in Android and as a background app in iOS. I need to get the ConnectionState information from this to any Xamarin.Forms UI that happens to be present.

Currently I use an interface for this thus:

  public interface IBleComms
    {
        void ConnectToDevice(Guid DeviceGuid);

        event EventHandler<BleConnectionState.ProteusConnectionStatus> ProteusConnectionStateChangedEvent;

        BleConnectionState.ProteusConnectionStatus GetProteusConnectionState();
    }

I implement the interface in my Xamarin.Android 'BleComms' class - snippet:

[assembly: Xamarin.Forms.Dependency(typeof(BleComms))]
namespace ProteusPatientApp.Droid
{

    public class BleComms : IBleComms
    {
        private static IDevice ProteusDevice = null;

        public Guid ProteusGuid { get; private set; } = Guid.Empty;

        private static IBluetoothLE ble = null;
        private static Plugin.BLE.Abstractions.Contracts.IAdapter adapter = null;

        private BleConnectionState.ProteusConnectionStatus CurrentProteusConnectionState = BleConnectionState.ProteusConnectionStatus.Unknown;

         #region Interface  

         public event EventHandler<BleConnectionState.ProteusConnectionStatus> ProteusConnectionStateChangedEvent;
         public BleConnectionState.ProteusConnectionStatus GetProteusConnectionState() => CurrentProteusConnectionState;

     public void UpdateProteusConnectionState(BleConnectionState.ProteusConnectionStatus state)
         {
             CurrentProteusConnectionState = state;
             ProteusConnectionStateChangedEvent?.Invoke(this, state);
             proteusConnectionStatusNotification.UpdateNotification(state);
         }

         public void ConnectToProteus(Guid proteusGuid)
         {
             SetProteusGuid(proteusGuid);
             SetStoredProteusGuid(proteusGuid);
         }

         #endregion

        public BleComms()
        {
            ble = CrossBluetoothLE.Current;
            adapter = CrossBluetoothLE.Current.Adapter;
            adapter.ScanMode = ScanMode.LowLatency;
            adapter.ScanTimeout = 30000;

    .........
        .........
    }
    }
}

Methods within BleComms call UpdateProteusConnectionState, which in turn triggers an event 'ProteusConnectionStateChangedEvent' that my UI code subscribes to.

This class is instantiated once by my Android service when it starts:

 public class ProteusService : Service
    {
        static readonly string TAG = "X:" + typeof(ProteusService).Name;
        bool isStarted = false;
        CancellationTokenSource _cts;
        private static BleComms bleComms;

        public override void OnCreate()  {  }

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            if (!isStarted)
            {
                bleComms = new BleComms();
                isStarted = true;
            }
            return StartCommandResult.Sticky;
        }
}

In my Xamarin.forms viewmodel code, I subscribe to the ProteusConnectionStateChangedEvent thus:

 DependencyService.Get<IBleComms>().ProteusConnectionStateChangedEvent += ConnectionStateChanged;
//ConnectionStateChanged is a method that updates the UI

I connect to my device thus:

DependencyService.Get<IBleComms>().ConnectToProteus(ProteusGuid);

The code works, but my BleComms class it gets instantiated **TWICE **- once by the Android service and then once again, on the first call through from the dependency service.

What I want to do is to have the BleComms class instantiated **ONCE ** as a singleton by the Service when it starts up, and have the dependency service obtain the results from the pre-existing instance rather than creating a new instance of BleComms.

Currently to get this working, I had to make some stuff within BleComms static - I suspect this is not the right way to do this, but using the MessagingService for this seems a but crude also - especially when I add the rest of the code and have loads of textural messages flying about the place. I did move the interface implementation into its own class, but that made setting the ProteusConnectionStateChangedEvent difficult.

I am new to interfaces and Xamarin Architecture, if anyone has a better suggestion, I would be interested to hear it!

Nigel

DataBinding not working for custom control :(

$
0
0

Hello,

I have problems to get DataBinding in my Xaml View Working.

My project uses the eShopOnContainers structure, using TinyIoC for dependency injections, ViewModelBase and so on.

The view uses a custom component I made, it has a MenuEntries bindable property that I bind to the MenuEntries of the ViewModel.

The view :

<?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:services="clr-namespace:MyProject.Services;assembly=MyProject"
    xmlns:components="clr-namespace:MyProject.Components;assembly=MyProject"
    x:Class="MyProject.Views.MenuOwnerView"
    services:DependencyLocator.AutoWireViewModel="true">
    <ContentPage.Content>
        <StackLayout Style="{StaticResource header}" Spacing="0">

            <components:Menu x:Name="Menu" MenuEntries="{Binding MenuEntries}"/> <!-- This is the binding I want to see working -->

        </StackLayout>
    </ContentPage.Content>
</ContentPage>

The ViewModel defines an ObservableCollection property. It's statically populated (no db or api call). When debugging, I can see that I valuate the property with some entries. The RaisePropertyChanged is called, and the OnPropertyChanged is called with the right property name.

The ViewModel :

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using MyProject.Locales.Resx;
using MyProject.Models;
using MyProject.Services.Navigation;

namespace MyProject.ViewModels
{
    public class MenuOwnerViewModel : Base.ViewModelBase
    {
        private INavigationService _navigationService;

        private ObservableCollection<MenuEntry> _MenuEntries;
        public ObservableCollection<MenuEntry> MenuEntries {
            get => _MenuEntries;
            set {
                // After calling InitializeAsync I succesfully run this code, RaisePropertyChanged is called on the MenuEntries property
                _MenuEntries = value;
                RaisePropertyChanged(() => MenuEntries);
            }
        }

        /*
         * ctor
         */
        public MenuOwnerViewModel(INavigationService navigationService)
        {
            _navigationService = navigationService;
        }

        public override Task InitializeAsync(object navigationData)
        {
            MenuEntries = InitMenuEntries();

            return Task.FromResult(true);
        }

        private ObservableCollection<MenuEntry> InitMenuEntries()
        {
            var entries = new ObservableCollection<MenuEntry>();

            entries.Add(new MenuEntry()
            {
                IconName = "menu-home",
                Title = "Homepage",
                IsActive = true,
            });

            return entries;
        }
    }
}

I created a component that has a BindableProperty to get its MenuEntries. Using Xaml DataBinding, I never go throught the property setter. If in code behind I manually valuate the property, everything works fine.

The component :

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

using Xamarin.Forms;

using MyProject.Models;
using MyProject.Interfaces;

namespace MyProject.Components
{
    public class Menu : ScrollView
    {
        public static readonly BindableProperty MenuEntriesProperty = BindableProperty.Create(
            propertyName: "MenuEntries",
            returnType: typeof(ObservableCollection<MenuEntry>),
            declaringType: typeof(Menu)
        );

        public ObservableCollection<MenuEntry> MenuEntries
        {
            get { return (ObservableCollection<MenuEntry>)GetValue(MenuEntriesProperty); }
            set {
                // I never run this code
                SetValue(MenuEntriesProperty, value); 
                RenderMenu();
            }
        }

        public Menu()
        {
            RenderMenu();
        }

        public void RenderMenu()
        {
            // Renders sub components
        }
    }
}

What did I missed ? What could I do to track the problem ? Is there so way to debug how databinding is implemented ?

Thank you !

Xamarin.Forms Cross-Platform templates missing on Visual Studio 2017

$
0
0

I've have tried almost every possible solution found on internet. Uninstalling components and reinstalling but still not able to get "cross-platform App (Xamarin.Forms or native)" template in my visual studio.
even Repairing visual studio did not help.


Reentrancy exception when adding View to StackLayout.Children from ItemSource and DataTemplate

$
0
0

Hello,

I stumble on a very simple thing here and I can't understand why! I am doing a templated StackLayout and I got a reentrancy exception (InvalidOperationException) when calling Children.Add inside a ItemSource_OnCollectionChanged. I just don't understand why because the two collections are just not the same !
I had a look at this thread and it appears there is the same issue.

I saw an example on the forum that rely on this behaviour. Is it a regression ? Do I do something dumb ??

Here is the code:

Control:

public class TemplateStackLayout : StackLayout
{
    private Stack<View> _viewCache;

    public TemplateStackLayout() : this(4)
    {
    }

    protected TemplateStackLayout(int capacity)
    {
        _viewCache = new Stack<View>(capacity);
    }

    protected virtual View CreateDefault(object item) => new Label { Text = item?.ToString() ?? null};

    protected virtual bool ValidateItemTemplate(DataTemplate dataTemplate) => true;

    protected virtual async void ItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        var dataTemplate = ItemTemplate;
        View content = null;
        object item = null;

        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                {
                    var offset = e.NewStartingIndex < 0 ? Children.Count : e.NewStartingIndex;

                    for (var i = 0; i < e.NewItems.Count; i++)
                    {
                        item = e.NewItems[i];
                        content = CreateContent(item, dataTemplate);
                        content.Parent = this;
                        content.BindingContext = item;
                        Children.Insert(offset + i, content);   //  Boom
                    }
                }
                break;
            case NotifyCollectionChangedAction.Move:
                {

                }
                break;
            case NotifyCollectionChangedAction.Remove:
                {

                }
                break;
            case NotifyCollectionChangedAction.Replace:
                {

                }
                break;
            case NotifyCollectionChangedAction.Reset:
                SetChildrenContentTo(ItemsSource);
                break;
            default:
                break;
        }
    }

    private void Recycle(View view)
    {
        if (view == null) return;

        view.BindingContext = null;
        view.Parent = null;
        _viewCache.Push(view);
    }

    private void SetChildrenContentTo(IEnumerable source)
    {
        if (source == null) return;

        var dataTemplate = ItemTemplate;
        View content = null;

        Children.Clear();

        foreach (var item in source)
        {
            content = CreateContent(item, dataTemplate);
            content.Parent = this;
            content.BindingContext = item;
            Children.Add(content);
        }
    }

    private View CreateContent(object item, DataTemplate dataTemplate)
    {
        View content = null;

        //  Try pop
        if (_viewCache.Count > 0 && (content = _viewCache.Pop()) != null)
        {
        }
        else if (dataTemplate != null)
        {
            content = (View)dataTemplate.CreateContent();
        }
        else
        {
            content = CreateDefault(item);
        }

        return content;
    }

    #region ItemsSource (Bindable IEnumerable)
    /// <summary>
    /// Manages the binding of the <see cref="ItemsSource"/> property
    /// </summary>
    public static readonly BindableProperty ItemsSourceProperty
        = BindableProperty.Create(propertyName: nameof(ItemsSource),
                                    returnType: typeof(IEnumerable),
                                    declaringType: typeof(TemplateStackLayout),
                                    defaultValue: default(IEnumerable),
                                    defaultBindingMode: BindingMode.OneWay,
                                    propertyChanging: ItemsSourceChanging,
                                    propertyChanged: ItemsSourceChanged);

    public IEnumerable ItemsSource { get => (IEnumerable)GetValue(ItemsSourceProperty); set => SetValue(ItemsSourceProperty, value); }

    private static void ItemsSourceChanging(BindableObject bindable, object oldValue, object newValue)
    {
        var control = (TemplateStackLayout)bindable;

        if (oldValue == null) return;

        if(oldValue is INotifyCollectionChanged ncc)
        {
            ncc.CollectionChanged -= control.ItemsSourceCollectionChanged;
        }

        foreach (var view in control.Children)
        {
            control.Recycle(view);
        }

        control.Children.Clear();
    }

    private static void ItemsSourceChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var control = (TemplateStackLayout)bindable;

        if (newValue == null) return;

        if(newValue is INotifyCollectionChanged ncc)
        {
            ncc.CollectionChanged += control.ItemsSourceCollectionChanged;
        }

        control.SetChildrenContentTo((IEnumerable)newValue);
    }
    #endregion  //  ItemsSource (Bindable IEnumerable)

    #region ItemTemplate (Bindable DataTemplate)
    /// <summary>
    /// Manages the binding of the <see cref="ItemTemplate"/> property
    /// </summary>
    public static readonly BindableProperty ItemTemplateProperty
        = BindableProperty.Create(propertyName: nameof(ItemTemplate),
                                    returnType: typeof(DataTemplate),
                                    declaringType: typeof(TemplateStackLayout),
                                    defaultValue: default(DataTemplate),
                                    defaultBindingMode: BindingMode.OneWay,
                                    propertyChanged: ItemTemplateChanged);

    private static void ItemTemplateChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var control = (TemplateStackLayout)bindable;
        control.Children.Clear();
        control._viewCache.Clear();

        var source = control.ItemsSource;
        if (source != null) control.SetChildrenContentTo(source);
    }

    private static bool ValidateItemTemplate(BindableObject bindable, object value)
    {
        var control = (TemplateStackLayout)bindable;
        return control.ValidateItemTemplate((DataTemplate)value);
    }

    public DataTemplate ItemTemplate { get => (DataTemplate)GetValue(ItemTemplateProperty); set => SetValue(ItemTemplateProperty, value); }
    #endregion  //  ItemTemplate (Bindable DataTemplate)
}

Page/ViewModel/Model

<?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="AppTest.Views.TemplateStackLayoutTestPage"
             xmlns:Views="clr-namespace:AppTest.Views"
             BindingContext="{StaticResource TemplateStackLayoutTestViewModel}">
    <ContentPage.Resources>
        <ResourceDictionary>
            <Views:TemplateStackLayoutTestViewModel x:Key="TemplateStackLayoutTestViewModel" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <StackLayout>
            <Button Text="Add" Command="{Binding Add}" />
            <Views:TemplateStackLayout ItemsSource="{Binding Source}">
                <Views:TemplateStackLayout.ItemTemplate>
                    <DataTemplate>
                        <Label Text="{Binding Text}" TextColor="Blue" />
                    </DataTemplate>
                </Views:TemplateStackLayout.ItemTemplate>
            </Views:TemplateStackLayout>
                    <Label Text="End" TextColor="Red" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

public partial class TemplateStackLayoutTestPage : ContentPage
{
    public TemplateStackLayoutTestPage ()
    {
        InitializeComponent ();
    }
}

class TemplateStackLayoutTestViewModel
{
    public TemplateStackLayoutTestViewModel()
    {
        Add = CommandFactory.Create(() => Source.Add(new TemplateStackLayoutTestModel() { Text = Guid.NewGuid().ToString() }));
    }

    public ObservableCollection<TemplateStackLayoutTestModel> Source { get; } = new ObservableCollection<TemplateStackLayoutTestModel>();

    public ICommand Add { get; }
}

class TemplateStackLayoutTestModel
{
    public string Text { get; set; }
}

Tested on a Galaxy A3 2016 with Android 6.0.1 and on the VS Emulator with Android 4.4 in Debug and shared runtime
Nuget: Xamarin Forms v2.5.0.280555

Trace (from the Galaxy):

    04-18 11:11:57.872 I/MonoDroid(15990): UNHANDLED EXCEPTION:
04-18 11:11:57.922 I/MonoDroid(15990): System.InvalidOperationException: Cannot change ObservableCollection during a CollectionChanged event.
04-18 11:11:57.922 I/MonoDroid(15990):   at System.Collections.ObjectModel.ObservableCollection`1[T].CheckReentrancy () [0x0002f] in <bcdc1df2b3724ab69797f3819a126346>:0 
04-18 11:11:57.922 I/MonoDroid(15990):   at System.Collections.ObjectModel.ObservableCollection`1[T].RemoveItem (System.Int32 index) [0x00000] in <bcdc1df2b3724ab69797f3819a126346>:0 
04-18 11:11:57.922 I/MonoDroid(15990):   at System.Collections.ObjectModel.Collection`1[T].Remove (T item) [0x00027] in <fcbf47a04b2e4d90beafbae627e1fca4>:0 
04-18 11:11:57.922 I/MonoDroid(15990):   at Xamarin.Forms.Layout.OnInternalAdded (Xamarin.Forms.View view) [0x0000b] in D:\agent_work\1\s\Xamarin.Forms.Core\Layout.cs:414 
04-18 11:11:57.922 I/MonoDroid(15990):   at Xamarin.Forms.Layout.InternalChildrenOnCollectionChanged (System.Object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) [0x00089] in D:\agent_work\1\s\Xamarin.Forms.Core\Layout.cs:406 
04-18 11:11:57.922 I/MonoDroid(15990):   at (wrapper delegate-invoke) <Module>.invoke_void_object_NotifyCollectionChangedEventArgs(object,System.Collections.Specialized.NotifyCollectionChangedEventArgs)
04-18 11:11:57.922 I/MonoDroid(15990):   at System.Collections.ObjectModel.ObservableCollection`1[T].OnCollectionChanged (System.Collections.Specialized.NotifyCollectionChangedEventArgs e) [0x0000f] in <bcdc1df2b3724ab69797f3819a126346>:0 
04-18 11:11:57.922 I/MonoDroid(15990):   at System.Collections.ObjectModel.ObservableCollection`1[T].OnCollectionChanged (System.Collections.Specialized.NotifyCollectionChangedAction action, System.Object item, System.Int32 index) [0x00009] in <bcdc1df2b3724ab69797f3819a126346>:0 
04-18 11:11:57.922 I/MonoDroid(15990):   at System.Collections.ObjectModel.ObservableCollection`1[T].InsertItem (System.Int32 index, T item) [0x00024] in <bcdc1df2b3724ab69797f3819a126346>:0 
04-18 11:11:57.922 I/MonoDroid(15990):   at System.Collections.ObjectModel.Collection`1[T].Add (T item) [0x00020] in <fcbf47a04b2e4d90beafbae627e1fca4>:0 
04-18 11:11:57.922 I/MonoDroid(15990):   at Xamarin.Forms.ObservableWrapper`2[TTrack,TRestrict].Add (TRestrict item) [0x0004b] in D:\agent_work\1\s\Xamarin.Forms.Core\ObservableWrapper.cs:35 
04-18 11:11:57.922 I/MonoDroid(15990):   at AppTest.Views.TemplateStackLayout+<ItemsSourceCollectionChanged>d__5.MoveNext () [0x000ee] in C:\Projects\Mobile\AppTest\AppTest\Views\TemplateStackLayout.cs:47

Street address from latitude and longitude in Xamarin.forms

$
0
0

Hello

We have an application in xamarin.froms where we are required to display street address based on latitude and longitude. There are so many examples out there but all are required google map api key to get street address. We don't want to use it because google's api key is not free. Is there any other way to get address based on latitude and longitude without google map api key ?

Regards
Tan

ControlTemplate Triggers

$
0
0

I'm trying to use Triggers in my ControlTemplate but the control is not updating. I have tried using both basic property Trigger and DataTrigger. Has anyone used Triggers in a ControlTemplate in Xamarin based on a Parent / TemplatedParent custom control's property? I have tried every variation of binding and Property setting I can think of. I'm starting to think that what I'm trying to do will just not work.

Any insight appreciated. Thanks!

<ControlTemplate x:Key="LabeledFieldTemplate">
            <Grid Margin="3,3,3,3"
              HorizontalOptions="StartAndExpand"
              VerticalOptions="StartAndExpand">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>

                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>

                <!--Default is "Above"-->
                <Label x:Name="LabelText"
                               Grid.Row="0"
                               Grid.Column="0"
                               FontSize="12"
                               TextColor="DarkGoldenrod"
                               Text="Test Text">
                    <Label.Triggers>
                        <Trigger TargetType="Label" Property="controls:LabeledField.LabelPosition" Value="None">
                            <Setter Property="IsVisible" Value="False" />
                        </Trigger>

                        <Trigger TargetType="Label" Property="controls:LabeledField.LabelPosition" Value="Right">
                            <Setter Property="Grid.Column" Value="1"/>
                            <Setter Property="Grid.Row" Value="0"/>
                            <Setter Property="Label.TextColor" Value="Purple"/>
                            <Setter Property="VerticalOptions" Value="Start" />
                            <Setter Property="WidthRequest" Value="{TemplateBinding LabelColumnWidth}" />
                            <Setter Property="Margin" Value="{TemplateBinding LabelPaddingWhenRight}" />
                        </Trigger>


                        <DataTrigger TargetType="Label" Binding="{TemplateBinding BindingContext.LabelPosition}" Value="Left">
                            <Setter Property="Grid.Column" Value="0"/>
                            <Setter Property="Grid.Row" Value="0"/>
                            <Setter Property="Label.TextColor" Value="Green"/>
                            <Setter Property="VerticalOptions" Value="Start" />
                            <Setter Property="WidthRequest" Value="{TemplateBinding LabelColumnWidth}" />
                            <Setter Property="Margin" Value="{TemplateBinding LabelPaddingWhenLeft}" />
                        </DataTrigger>


                        <DataTrigger TargetType="Label" Binding="{Binding LabelPosition}" Value="Above">
                            <Setter Property="Grid.Column" Value="0"/>
                            <Setter Property="Grid.Row" Value="0"/>
                            <Setter Property="Label.TextColor" Value="Orange"/>
                            <Setter Property="VerticalOptions" Value="End" />
                            <Setter Property="HeightRequest" Value="-1" />
                            <Setter Property="WidthRequest" Value="{Binding Width, Source={x:Reference Content}}" />
                            <Setter Property="Margin" Value="{TemplateBinding LabelPaddingWhenAbove}" />
                        </DataTrigger>


                        <DataTrigger TargetType="Label" Binding="{TemplateBinding Parent.LabelPosition}" Value="Below">
                            <Setter Property="Grid.Column" Value="0"/>
                            <Setter Property="Grid.Row" Value="1"/>
                            <Setter Property="Label.TextColor" Value="Blue"/>
                            <Setter Property="VerticalOptions" Value="End" />
                            <Setter Property="HeightRequest" Value="-1" />
                            <Setter Property="WidthRequest" Value="{Binding Width, Source={x:Reference Content}}" />
                            <Setter Property="Margin" Value="{TemplateBinding LabelPaddingWhenBelow}" />
                        </DataTrigger>
                    </Label.Triggers>
                </Label>

                <ContentPresenter x:Name="Content"
                                          Grid.Row="1"
                                          Grid.Column="0"
                                          VerticalOptions="CenterAndExpand">
                    <ContentPresenter.Triggers>
                        <DataTrigger TargetType="ContentPresenter" Binding="{TemplateBinding Parent.LabelPosition}" Value="Right">
                            <Setter Property="Grid.Column" Value="0"/>
                            <Setter Property="Grid.Row" Value="0"/>
                        </DataTrigger>

                        <DataTrigger TargetType="ContentPresenter" Binding="{TemplateBinding Parent.LabelPosition}" Value="Left">
                            <Setter Property="Grid.Column" Value="1"/>
                            <Setter Property="Grid.Row" Value="0"/>
                        </DataTrigger>

                        <DataTrigger TargetType="ContentPresenter" Binding="{TemplateBinding Parent.LabelPosition}" Value="Above">
                            <Setter Property="Grid.Column" Value="0"/>
                            <Setter Property="Grid.Row" Value="1"/>
                        </DataTrigger>

                        <DataTrigger TargetType="ContentPresenter" Binding="{TemplateBinding Parent.LabelPosition}" Value="Below">
                            <Setter Property="Grid.Column" Value="0"/>
                            <Setter Property="Grid.Row" Value="0"/>
                        </DataTrigger>
                    </ContentPresenter.Triggers>
                </ContentPresenter>
            </Grid>
        </ControlTemplate>

Here is a snippet of code that defines the LabelPosition property on the LabeledField class

    public static readonly BindableProperty LabelPositionProperty = BindableProperty.Create(
        "LabelPosition",
        typeof(LabelPosition),
        typeof(LabeledField),
        LabelPosition.Right,
        propertyChanged: UpdateLayout);

    public LabelPosition LabelPosition
    {
        get => (LabelPosition)GetValue(LabelPositionProperty);
        set => SetValue(LabelPositionProperty, LabelPosition);
    }

    public static LabelPosition GetLabelPosition(BindableObject element)
    {
        return (LabelPosition)element.GetValue(LabelColumnWidthProperty);
    }

    public static void SetLabelPosition(BindableObject element, LabelPosition value)
    {
        element.SetValue(LabelPositionProperty, value);
    }

    private static void UpdateLayout(BindableObject bindable, object oldvalue, object newvalue)
    {
        var labeledField = bindable as LabeledField;
        //Calling this method will invalidate the measure and triggers a new layout cycle.
        //labeledField?.InvalidateLayout();

        //labeledField?.UpdateChildrenLayout();
        labeledField?.ForceLayout();
    }

Pass page-specific data from Xamarin.Android into Xamarin.Forms via App.xaml.cs App() constructor

$
0
0

Hi

My android app launches a Xamarin.Forms page depending on the nature of the intent it receives.

My Xamarin.Android app loads the Xamarin.forms page through MainActivity using one of two methods:

1) If the Activity needs to be started, it calls LoadApplication(new App(requestedPageId));
2) If the activity is already running, it sends a message to the currently active forms App() using the MessagingCenter to request a page switch

For each Xamarin.Forms Page that is launched, I need to pass a different data 'payload' into Xamarin.Forms. The data within will be used to construct the page.

I am aware that there are several ways to do this, but unsure whether I am going at it the right way.

1) Overload the 'App' constructor having a different one for every page (5 pages) and passing all my data into the App class using a struct (different struct for each page)
2) Record the data down in the native code, and call LoadApplication(App(pageId)), passing in a pageId. In App(), switch on the PageId, and call an interface through the DependencyService to obtain the data required for displaying that page. Android would implement the interface to spit out the required data - this has a few advantages in that the ViewModel for the page can be the thing that calls the DependencyService to grab the data for display.

Is there a better way?? - if I were doing this in C, then I would pass a void pointer to a struct containing the data, and then cast this to the required type in App() - Can I do something similar using LoadApplication(App()), and a delegate?

Nigel

Xamarin.Forms Xaml to add icon image next to user name and password field

$
0
0

Does anyone know how to add an image next to a Text field used for data entry? I can't figure this out. I even tried to create an ImageCell.

Here is my code. This code centers the icon image just above the Text entry field.

<StackLayout Padding="20" Spacing="10" VerticalOptions="Center" Grid.Row="1" Grid.Column="0">
        <StackLayout Spacing="5">
          <Image Source="User_Profile_48.png" />
            <local:LineEntry Placeholder="email address" HorizontalOptions="FillAndExpand"
                             Text="{Binding UserName, Mode=TwoWay}"
                             Style="{StaticResource LineEntryStyle}" />  

          <Image Source="Briefcase_02_48.png" />
          <local:LineEntry Placeholder="password" IsPassword="True"
                           Text="{Binding UserPassword, Mode=TwoWay}"
                           Style="{StaticResource LineEntryStyle}" />
 </StackLayout>

Any help is much appreciated.

Thanks!

Viewing all 58056 articles
Browse latest View live


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