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

Xamarin Forms MVVM parent / child example?

$
0
0

Is there a parent / child example out there somewhere? I’ve not seen one out there.

To be clear, I am not referring to a MasterDetailPage.

I am using Visual Studio 2017 Mac with a netstandard2.0 Xamarin Forms iOS / Android project solution. I’ve added sqlite-net-pcl version 1.4.118 NuGet; using XF version 3.1.0.x. I tried using the sqlite-net Extensions, but that crashes when I try to use OneToMany / ManyToOne.

Two models: a Player and Team (see below).

There can be many Players. A team can have 1 to many Players on it.

There are plenty of examples how to deal with the MVVM child (Player), so no examples need for that. I wanted a ContentPage that would allow the user to enter a new Team (name) at the top and a ListView / Grid of Players for that team via a Switch or Checkbox listed below the team name.

Models:
namespace Project.Models
 {

[Table(“Player”)]

public class Player

{

[PrimaryKey, AutoIncrement]

public int Id { get; set; }
public string Name { get; set; }

public string Position { get; set; }

}

}

namespace Project.Models
 {

 [Table(“Team”)]

public class Team

{

 [PrimaryKey, AutoIncrement]

public int Id { get; set; }

 public string Name { get; set; }

 public List Players { get; set; }

}

}

Note: the List Players will generate a runtime error. Note: I did think of a way to stuff the int list into a string and get it back out as a int list; however, I thought it important to get the concept across rather than it correctly working but a muddled.

That said, I’d think that this should be a (relatively speaking) common design pattern and I’d like to see an MVVM example of how to do this. I’ve searched the forum, but didn’t see any non-native XF example. I’ve also done a Bing search and didn’t find it an example there either.

Can anyone point me to some good links?


The "LinkAssemblies" task failed unexpectedly.

$
0
0

I´m trying to reduce the APK size to publish in Play Store.
I´m using VS 2017 and "Linking" in the Android Options

I tried with Sdk and User Assemblies and Sdk Assemblies Only either are not working.

I got the next error:

The "LinkAssemblies" task failed unexpectedly.
Java.Interop.Tools.Diagnostics.XamarinAndroidException: error XA2006: Could not resolve reference to 'System.Diagnostics.CounterCreationData' (defined in assembly 'System.Data.OracleClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') with scope 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. When the scope is different from the defining assembly, it usually means that the type is forwarded. ---> Mono.Cecil.ResolutionException: Failed to resolve System.Diagnostics.CounterCreationData
at Mono.Linker.Steps.MarkStep.HandleUnresolvedType(TypeReference reference)
at Mono.Linker.Steps.MarkStep.MarkType(TypeReference reference)
at MonoDroid.Tuner.MonoDroidMarkStep.MarkType(TypeReference reference)
at Mono.Linker.Steps.MarkStep.MarkField(FieldReference reference)
at Mono.Linker.Steps.MarkStep.InitializeFields(TypeDefinition type)
at Mono.Linker.Steps.MarkStep.InitializeType(TypeDefinition type)
at Mono.Linker.Steps.MarkStep.InitializeType(TypeDefinition type)
at Mono.Linker.Steps.MarkStep.InitializeAssembly(AssemblyDefinition assembly)
at Mono.Linker.Steps.MarkStep.Initialize()
at Mono.Linker.Steps.MarkStep.Process(LinkContext context)
at Mono.Linker.Pipeline.Process(LinkContext context)
at MonoDroid.Tuner.Linker.Process(LinkerOptions options, ILogger logger, LinkContext& context)
at Xamarin.Android.Tasks.LinkAssemblies.Execute(DirectoryAssemblyResolver res)
--- End of inner exception stack trace ---
at Java.Interop.Tools.Diagnostics.Diagnostic.Error(Int32 code, Exception innerException, String message, Object[] args)
at Xamarin.Android.Tasks.LinkAssemblies.Execute(DirectoryAssemblyResolver res)
at Xamarin.Android.Tasks.LinkAssemblies.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.d__26.MoveNext() CloudParkingApp.Android

EventToCommand with Xamarin Forms Behaviors

$
0
0

I wrote an EventToCommand behavior using Xamarin Forms 1.3 behaviors and I would like to share it with you : anthonysimmon.com/eventtocommand-in-xamarin-forms-apps/

You will find an example where the EventToCommand is bound to the ItemTapped of a ListView so that we can get the tapped item data context inside a command of the ListView data context:

<ListView ItemsSource="{Binding People}">
  <ListView.Behaviors>
    <b:EventToCommandBehavior EventName="ItemTapped" Command="{Binding SayHelloCommand}" EventArgsConverter="{StaticResource ItemTappedConverter}" />
  </ListView.Behaviors>
  <ListView.ItemTemplate>
    <DataTemplate>
      <TextCell Text="{Binding Name}"/>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

set custom font in webview

$
0
0

I want to set my own custom font in webview.

WebView Description = new WebView(this.Context); WebSettings settings = Description.Settings; settings.FixedFontFamily = "DIN-Condensed-Bold.ttf";

I have added my Font called DIN-Condensed-Bold.ttf in Assets/fonts folder, but I don`t see the effect.
Is it build action problem? How can I implement it?

Azure SQL Database without an Azure App Service plan ?

$
0
0

Hi !

I want to build a Xamarin.Forms app using only one Azure SQL Database.

My question is : is it possible to use an Azure database without an App Service subscription ? I just want to pay for the database (I have a small budget).

If it is, I was not able to find a proper tutorial describing how to connect to this database (all tutorial show how to use the database with App Service)

Thanks !

VideoPlayer xamarin forms

$
0
0

Hi xamarin forum
Can anyone give a suggestion where can I find a video player that
1. Can play my video from database using file path
2. can really work on both iOS and Android

I said the number 2 because I am currently using the sample code that is written here

https://developer.xamarin.com/samples/xamarin-forms/customrenderers/VideoPlayerDemos/

but when I tried in my iOS device it crashes my app but when I use it in my Android device all works fine @BillyLiu (Thanks for all the help dude! Cheers!)

Navigation Master Page Issue

$
0
0

Hello - I'm developing an Android/iOS app with Xamarin Forms which relies on the Navigation Master Detail page for its main navigation.
I've tested my app on Android and iOS simulators and it is working as intended. When I test it on a physical iPad however, the navigation menu is empty. The menu button and pop out work correctly, the pop out menu looks correct, but where there should be a list is just blank.

I've double checked font sizes, colors, label bindings etc - I don't think it's a UI problem.

The iOS simulator I'm using is running iOS 11.4 whereas the iPad I'm using is running iOS 9.3.5
Could it be the OS version?

Has anyone else seen this?

HOW TO ACCESS THE FILE PATH IN IOS DEVICE

$
0
0

Hi,

I'm working for download/upload files like image, docs and video in Xamarin.Forms IOS. I use PCLStorage from Nuget. My question is that how can I access the filepath like this:

this path is on my emulator in Mac:
/Users/mac-name/Library/Developer/CoreSimulator/Devices/138067AE-00A4-4B9B-BCDA-15133F13A/data/Containers/Data/Application/850D57E6-50AD-40D0-A5E3-30745C21/Documents/../Library/ImageTest
I've see the image save in this path in imac folder.

this path is in my iphone:
/var/mobile/Containers/Data/Application/9B119CB1-47AD-49B9-80B3-7228D52C/Documents/../Library/ImageTest
I want also to see this in folder files/ or File Manager in Iphone like android.

If anyone of you guys who already tried this or any best way to fix my issue please give some advice.

Thanks in advance!


Unable to activate instance of type Xamarin.Forms.Platform.Android.ListViewAdapter

$
0
0

I don't know why I am getting this error. I am using MVVM and a listview. What I am trying to use is that I am fetching some info from Backend with the help of MVVM. I want that my listview should be updated when I am adding an item. Everything is working fine except the listview, neither it is updated nor unable to remove an item.

Here is my code

List<string> items = new List<string>();
    ObservableCollection<UserCartDetails> cart_response = new ObservableCollection<UserCartDetails>();
    ShoppingServices shoppingServices = new ShoppingServices();
    //UserCartDetails Item = new UserCartDetails();
    public static Context _context = Android.App.Application.Context;

#region "Refreshing Data"
    private bool isLoading;
    private bool isRefreshing;
    public bool IsLoading
    {
        get
        {
            return this.isLoading;
        }

        set
        {
            this.isLoading = value;
            RaisePropertyChanged("IsLoading");
        }
    }
    public bool IsRefreshing
    {
        get
        {
            return this.isRefreshing;
        }

        set
        {
            this.isRefreshing = value;
            RaisePropertyChanged("IsRefreshing");
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }
    public Command RefreshCommand
    {
        get
        {
            return new Command(async () =>
            {
                await BindData();
            });
        }
    }
    #endregion

private async Task BindData()
    {
        //cart_response.Clear();
        var response1 = shoppingServices.GetCartDetail(BaseClass.UserId, BaseClass.Kitchen_Id, BaseClass.Token);
        if (response1.success == "True")
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                cart_response = response1.parameters;
                ResponseList.ItemsSource = cart_response;
            });
           // cart_response = response1.parameters;

        }

        IsLoading = false;
        IsRefreshing = false;
    }
    private async void Button_Click(object sender, EventArgs e)
    {
        IsLoading = true;
        data.IsVisible = true;
        string name = entry_name.Text;
        string quantity = WeightList.SelectedItem.ToString().Split(' ')[0];
        var response = shoppingServices.CartDetail(BaseClass.UserId, BaseClass.Kitchen_Id, name, quantity, BaseClass.Token);
        if (response.success == "True")
        {
            await Task.Run(async () => { await BindData(); });
            //await BindData();
        }
    }
    void OnTapGestureRecognizerTapped2(object sender, EventArgs e)
    {
        //var item = (Xamarin.Forms.Image)sender;
        int cart_id = Convert.ToInt32(((Xamarin.Forms.TappedEventArgs)e).Parameter);
        var response = shoppingServices.RemoveCartDetail(BaseClass.UserId, cart_id.ToString(), BaseClass.Token);
        if (response.success == "True")
        {
            Toast.MakeText(_context, response.message, ToastLength.Long).Show();
            cart_response.Clear();
            ResponseList.ItemsSource = cart_response;
            if(ResponseList.ItemsSource==null)
            {
                ResponseList.IsVisible = false;
            }
            else
            {
                var response1 = shoppingServices.GetCartDetail(BaseClass.UserId, BaseClass.Kitchen_Id, BaseClass.Token);
                if (response1.success == "True")
                {
                    cart_response = response1.parameters;
                    ResponseList.ItemsSource = cart_response;
                }
            }
        }
        else
        {
            Toast.MakeText(_context, response.message, ToastLength.Long).Show();
        }
    }

Button Text alignment

$
0
0

Is there a way to change the text alignment in Button? I want to fix the alignment and color of the button for the entire app.

Thanks in advance

UWP project doesn't load after Visual Studio 15.7.6 update

$
0
0

After updating Visual Studio to 15.7.6, my Xamarin.Forms UWP project no longer loads with the error

error : Unterminated string. Expected delimiter: ". Path 'packages[252].localizedResources[8].description', line 1, position 853299.

The main project as well as the iOS and Android projects load just fine.

Tried re-creating an empty Xamarin.Forms project and the UWP project doesn't even get created, even though it's enabled. If I check the solution log, I see the exact same error message

Display Alert

$
0
0

Hi All,
I am using DisplayAlert for popup messages,In Ios it is fine
But in android button(cancel) is always in capital letters. how to have cancel button with small letters

Thankyou

SQLite.net NullReferenceException whilst following provided Xamarin example(s)

$
0
0

Hey guys,

Me again, with a different question about a different subject; SQLite.

I've got quite good skills in scripting SQL queries, but I'm struggling to connect my XamarinForms (Portable) solution to a local database.

I've followed the guide provided by Xamarin and their example on Github.

However, as mentioned I'm having some issues with connecting my already created solution with the database. Debugging my solution gives me nothing except an error message:

System.NullReferenceException: Object reference not set to an instance of an object.

in my for loop (looping through every object in a list of objects ):

foreach (Foundation found in result) { await App.Database.SaveItemAsync(found); count++; Debug.WriteLine(count.ToString()); }

result is the resulting set (List) from a call to a RESTful Api that most assuredly is NOT null, and is invoked after the result has been assigned to.

The reference to App.Dabatase.SaveItemAsync() is linked similar to the provided github example mentioned above.

Here is a linkto my project on Github. For the full source code, please see the referred Github link provided in previous sentence as it would be too much to write it all here.

The relevant files are App.cs, Data -> FoundationsDatabase.cs and GetFoundationsPage.cs

How to remove AppBar/Toolbar in WPF application in Xamarin.forms?

Can't build Xamarin.iOS app in Ad-Hoc,"Unexpected error-Please file a bug report at http://bugzilla"

$
0
0

Hi,

Our distribution license for our iOS app had gone out, so I have to rebuild our app that is distributed Ad-hoc.
But I have problems building the app without any changes being made.

It works running the app in development on a device, but fails when building for release or Ad-hoc.

I have attached the error-list and error-output, please can someone take a look and guide me how to resolve this issues?


Return to same page when app is back into foreground.

$
0
0

Hi,

The main page of my app is subscribed to receiving push notifications. When the app is in the foreground, the notification data is displayed on the page(when notification comes in).

When the app is in the background I want that when the user clicks the notification, the page with the push notification information is loaded.

If the page is in the background, is it still subscribed to receiving notifications and thus still receives notifications? Or clicking the notification in the notification tray just load a new page, re-subscribes and has missed the previous notification information?

How can I achieve this? Thank you in advance.

Xamarin Forms iphone simulator filenotfoundexception resources.dll

$
0
0

Hi, since a month when I start debugging my app in iphone simulator and access to a specific Page the debugger detects a System.IO.FileNotFoundException related to this path:

/Users/xxx/Library/Developer/CoreSimulator/Devices/CF741BB8-6814-4895-9BEE-76E8E82C9F11/data/Containers/Bundle/Application/685D5325-455C-405C-A600-D49E4A12EC78/xxx.iOS.app/en-US/Xamarin.Forms.Platform.iOS.resources.dll

I look inside the path and i don't found a folder named /en-US/

After that I change localization to Italian and a similar FileNotFoundException raised related to path:

/Users/xxx/Library/Developer/CoreSimulator/Devices/CF741BB8-6814-4895-9BEE-76E8E82C9F11/data/Containers/Bundle/Application/685D5325-455C-405C-A600-D49E4A12EC78/xxx.iOS.app/it-IT/Xamarin.Forms.Platform.iOS.resources.dll

Inside the app bundle there is the folder /it/ not the folder /it-IT/.

I tried to check XAML and sources for wrong references, paths and names without success.
I also checked and upgraded anything.

Can someone help me on this problem?

Calling a WebAPI

$
0
0

Hi, how can I call the webApi in Xamarin.Forms which I created .Net Standard? (See API code below)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.Web.Http;
using Microsoft.AspNetCore.Mvc;

namespace XMR.WebApplication.Controllers
{
    [Route("api")]
    [ApiController]
    public class MobileController : ControllerBase
    {
        [Route("Get")]
        [HttpGet]
        public string Get()
        {
            return "Hello WebAPI";
        }
    }
}

Custom Range Slider for iOS

$
0
0

For those who search to make a custom range slider in iOS, this is mine.

OneView.xaml in MyApp.Shared.Views :

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:c="clr-namespace:MyApp.Shared.Forms;assembly=MyApp.Shared" x:Class="Whymee.Shared.Views.OneView" Padding="0, 20, 0, 0"> <c:RangeSlider Minimum="0" Maximum="100" RangeValue="{Binding Minimum, Mode=TwoWay}" Value="{Binding Maximum, Mode=TwoWay}"/> </ContentPage>

OneViewModel.cs in MyApp.Shared.ViewModels :

`namespace MyApp.Shared.ViewModels
{
public class OneViewModel : ViewModelBase
{
#region Fields
private double _minimum;
private double _maximum;
#endregion

    #region Constructor
    public WantViewModel()
    {
        this._minimum = 0;
        this._maximum = 30;
    }
    #endregion

    #region Properties
    public double Minimum
    {
        get { return this._minimum; }
        set
        {
            this._minimum = value;
            this.RaisePropertyChanged("Minimum");
        }
    }

    public double Maximum
    {
        get { return this._maximum; }
        set
        {
            this._maximum = value;
            this.RaisePropertyChanged("Maximum");
        }
    }
    #endregion
}

}`

RangeSlider.cs in MyApp.Shared.Forms :

`namespace MyApp.Shared.Forms
{
public class RangeSlider : Slider
{
public static readonly BindableProperty RangeValueProperty = BindableProperty.Create<RangeSlider, double>(r => r.RangeValue, 0, BindingMode.TwoWay, null, null, null, null);

    public RangeSlider()
    {
    }

    public double RangeValue
    {
        get { return (double)GetValue(RangeValueProperty); }
        set { SetValue(RangeValueProperty, value); }
    }
}

}`

RangeSliderRenderer.cs in MyApp.iOS.Renderers :

`[assembly: ExportRenderer (typeof(RangeSlider), typeof(RangeSliderRenderer))]

namespace MyApp.iOS.Renderers
{
public class RangeSliderRenderer : SliderRenderer
{
private UISlider _rangeSlider;

    public RangeSliderRenderer()
    {
    }

    protected override void OnElementChanged(ElementChangedEventArgs<Slider> e)
    {
        base.OnElementChanged(e);
        if (e.OldElement != null || this.Element == null)
            return;

        this.InitSlider();
    }

    private void Element_SizeChanged(object sender, EventArgs e)
    {
        this.InitRangeSlider();
    }

    private void RangeSlider_PanGestureRecognized(UIPanGestureRecognizer recognizer)
    {
        this.SetThumbValue(recognizer.LocationInView (this.NativeView).X);
    }

    /**
    *** Custom functions
    **/

    private void InitSlider()
    {
        this.Control.MinimumTrackTintColor = UIColor.Blue;
        this.Control.MaximumTrackTintColor = UIColor.LightGray;

        this.Element.SizeChanged += Element_SizeChanged;
    }

    private void InitRangeSlider()
    {
        this._rangeSlider = new UISlider();
        this._rangeSlider.Value = (float)(this.Element as RangeSlider).RangeValue;
        this._rangeSlider.MinValue = (float)this.Element.Minimum;
        this._rangeSlider.MaxValue = (float)this.Element.Maximum;
        this._rangeSlider.MinimumTrackTintColor = UIColor.LightGray;
        this._rangeSlider.MaximumTrackTintColor = UIColor.Clear;
        this._rangeSlider.Frame = new System.Drawing.RectangleF(0, 0, (float)this.Element.Width, (float)this.Element.Height);

        UIPanGestureRecognizer panGestureRecognizer = new UIPanGestureRecognizer();
        panGestureRecognizer.AddTarget(() => RangeSlider_PanGestureRecognized(panGestureRecognizer));
        this._rangeSlider.AddGestureRecognizer(panGestureRecognizer);

        this.AddSubview(this._rangeSlider);
    }

    private void SetThumbValue(float x)
    {
        if (x <= this.Element.Width / this.Element.Maximum * (this.Element.Value + 10) && x >= this.Element.Width / this.Element.Maximum * (this.Element.Value - 10) && this._rangeSlider.Value < (float)(this.Element.Maximum / this.Element.Width * x))
            this.Element.Value = (float)(this.Element.Maximum / this.Element.Width * x);
        else if (x <= this.Element.Width / this.Element.Maximum * (this._rangeSlider.Value + 10) && x >= this.Element.Width / this.Element.Maximum * (this._rangeSlider.Value - 10) && this.Element.Value > (float)(this.Element.Maximum / this.Element.Width * x))
        {
            this._rangeSlider.Value = (float)(this.Element.Maximum / this.Element.Width * x);               
            (this.Element as RangeSlider).RangeValue = this._rangeSlider.Value;
        }
    }
}

}`

See u ;-)

How can I allow only my Xamarin App to access Easy Table and Easy API?

$
0
0

Hi,

I'm a newbie with Xamarin but have done C# programming in the past, I'm currently using Azure's Easy Table and soon Easy API. To increase security, I'd like to prevent other apps from accessing my Easy Tables and Easy APIs. I have set up my Easy Tables to "Allow anonymous access" right now, I believe I should set this to "Authenticated" to prevent other apps in accessing my Easy Tables and APIs.

So should I create one account maybe in Active Directory and use it in my app in the authentication process to only allow my app to access my Easy Tables and APIs?

Should I add an "ID" in my app and have the back end filter other requests that doesn't have the "ID"? And if so, how does one go about it? Should I modify the Node.JS script? How secure can this be?

Note, I have my own user authentication based on user email address and password and it is working okay, but this is on an application level authentication only(i.e., if users provides correct email address and password, they are able to order, view history, etc.). This obviously will not prevent other apps in accessing my Easy Tables and Easy APIs.

Thanks everyone!

Viewing all 91519 articles
Browse latest View live


Latest Images

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