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

How to detect key presses when nothing has focus.

$
0
0

Hello,

I am writing an app for an Android-based scanner. Scanned data is sent to the app as keystrokes (even though the keyboard is not displayed). This works great as long as an entry field has focus. However, it is pretty easy to have nothing focused, so then when the keystrokes come in, they are ignored.

I need a solution for when nothing has focus, so any sort of custom renderer won't help.

Because there are multiple entry fields on the screen, I cannot force focus to an entry field in an Unfocused event, because I can't tell if the control is losing focus because the user tapped on another entry field, or if it's because they've tapped "nowhere", or ... whatever other creative way there is to unfocus to nothing.

I'm using Xamarin Forms, but because this is for a specific Android-based device, I don't need it to work on any other platform.

Any ideas?

Thanks!
-Karen


modify image pixels in forms

$
0
0

Hi I want to change a collared image to greyscale before I show it on the screen. Can some one please tell me why my code below is not working?

     private byte[] ConvertMediaFileToByteArray(MediaFile file)
        {
            using (var memoryStream = new MemoryStream())
            {
                file.GetStream().CopyTo(memoryStream);
                return memoryStream.ToArray();
            }
        }

        public void LoadAndConvertImage(MediaFile imgPath){
            byte[] imgSrc = ConvertMediaFileToByteArray(imagePath);
            ConvertToGrayRemoveNoise(ref cropedBytes);

             ImageSource imageSource = ImageSource.FromStream(() =>
            {
                var cropedImage = new MemoryStream(cropedBytes);
                file.Dispose();
                return cropedImage;
            });
            Image Image.Source = imageSource;

        }
        public void ConvertToGray(ref byte[] srcPixels)
        {
            try
            {
                for (int i = 0; i < srcPixels.Length; i += 4)
                {
                    double b = (double)srcPixels[i] / 255.0;
                    double g = (double)srcPixels[i + 1] / 255.0;
                    double r = (double)srcPixels[i + 2] / 255.0;

                    byte a = srcPixels[i + 3];
                    //convert to gray
                    double e = (0.299 * r + 0.587 * g + 0.114 * b) * 255;

                    byte f = Convert.ToByte(e);

                    srcPixels[i] = f;
                    srcPixels[i + 1] = f;
                    srcPixels[i + 2] = f;
                    srcPixels[i + 3] = a;

                }
            }
            catch (Exception error)
            {
                Debug.WriteLine(error.ToString());
            }
        }

I see two issues. Sometime the ConvertToGray function runs into the Catch with a pointer out of range. If this does not happen the initialisation of the image fails with "initWithData returned nil". I would like to work with the byte[] as several plugins with crop also use that as input and output.

How to refresh list in xamarin form

$
0
0

Hello,

public class Product
{
public int ProductID { get; set; }
public string ProductName {get;set;}
public int Quantity { get; set; }
public double Price { get; set; }
}

List product=new List();

I am displaying a list of product and change the quantity of particular product. But it is not reflecting on screen. Is there any way to that using ViewModel approach?

ValueConverter with Bindable Property

$
0
0

I have a Xamarin project, and I am trying to get a binding on my ValueConverter. I accomplish this in my UWP project, but in Xamarin I am getting a compilation error:

No property, bindable property, or event found for 'UserData', or mismatching type between value and property.

The purpose of this is that when you select an item in the ListView, the entry reads the UserValue property, when you edit the text in this entry, the content of the item's property is updated, and this change is visible in the ListView.

There is my code:

MainPage.XAML:

    <ListView x:Name="_ListView" ItemSelected="_ListView_ItemSelected">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Grid>
                        <Grid.Resources>
                            <local:ViewCell_Converter x:Key="ViewCell_Converter" UserData="{Binding}"/>
                        </Grid.Resources>

                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="2*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <Label Grid.Column="0" Text="{Binding UserName}"/>
                        <Label Grid.Column="1" Text="{Binding UserValue, Converter={StaticResource ViewCell_Converter}}"/>
                    </Grid>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackLayout>

MainPage.XAML.cs:

public MainPage()
{
    InitializeComponent();

    _ListView.ItemsSource = UserDatas();
}        

private ObservableCollection<UserData> UserDatas()
{
    return new ObservableCollection<UserData>()
    {
        new UserData() { UserName = "Name1", UserValue = 10, ValidatedByUser = true, },
        new UserData() { UserName = "Name2", UserValue = 11, ValidatedByUser = false, },
        new UserData() { UserName = "Name3", UserValue = 12, ValidatedByUser = true, },
        new UserData() { UserName = "Name4", UserValue = 13, ValidatedByUser = false, },
        new UserData() { UserName = "Name5", UserValue = 14, ValidatedByUser = true, },
    };
}

private void _ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
    if (e.SelectedItem is UserData userData)
    {
        Entry_NewValue.Text = userData.UserValue.ToString();
    }
}

private void Entry_NewValue_TextChanged(object sender, TextChangedEventArgs e)
{
    if (_ListView.SelectedItem is UserData userData)
    {
        if (double.TryParse(Entry_NewValue.Text, out double _double))
        {
            if(userData.UserValue != _double)
            {
                userData.UserValue = _double;
            }                
        }
    }
}

Methods.cs:

public class UserData : Prism.Mvvm.BindableBase
{
    private bool _validatedByUser;
    public bool ValidatedByUser
    {
        get
        {
            return _validatedByUser;
        }
        set
        {
            SetProperty(ref _validatedByUser, value);
        }
    }

    private string _userName;
    public string UserName
    {
        get
        {
            return _userName;
        }
        set
        {
            SetProperty(ref _userName, value);
        }
    }

    private double _userValue;
    public double UserValue
    {
        get
        {
            return _userValue;
        }
        set
        {
            SetProperty(ref _userValue, value);
        }
    }
    }

    public class ViewCell_Converter : BindableObject, IValueConverter
    {            
    public UserData UserData
    {
        get { return (UserData)GetValue(bindableProperty); }
        set { SetValue(bindableProperty, value); }
    }

    public static readonly BindableProperty bindableProperty = BindableProperty.Create(
                                                               nameof(UserData),
                                                               typeof(UserData),
                                                               typeof(ViewCell_Converter),
                                                               null);

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (UserData != null)
        {
            if (value is double _value)
            {
                if (UserData.ValidatedByUser)
                {
                    return string.Format("{0:0.00}", _value);
                }
                else
                {
                    return string.Format("{0:0.0000}", _value);
                }
            }
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Ram/BatteryConsumption using Xamarin UI Test

$
0
0

Hello Folks,

I went through the Xamarin UI Test API https://developer.xamarin.com/api/namespace/Xamarin.UITest/.
I did not see any API to see RAM, battery consumption.
When I run the tests locally on a emulator is there any place I can see the consumption?
I Know you can see the RAM consumption when you run the tests on Test Cloud ( aka appCenter)

Global styles which are coded in visaul studio 2015 project are not working in VS 2017

$
0
0

Hi Guys,
Last year i have created a project of Xamarin forms in VS 2015 and i have wrote global styles in APP.xaml page they were working perfectly and and published also. Recently i have installed VS 2017 global styles of same project are not working at all.
How to solve the issue?

My entry placeholder text is cut by the half

$
0
0

Hi, I have a entry with a placeholder text I used that like a search bar, in some Android devices the text appears cut by the half, I try resize the FontSize but dons't work, anybody can help me?

Custom Renderer Not Working

$
0
0

So I've followed a YouTube video and the Microsoft docs on this but it still isn't working. I have a page with my custom renderer on it, which I've used the namespace for...
<local1:RoundedEntry Text="Test"/>

This comes from a .cs file

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Xamarin.Forms;

    namespace TestApp
    {
        public class RoundedEntry : Entry
        {
        }
    }

Then what exports to this file is this...

using Android.Content;
using TestApp;
using TestApp.Droid.CustomRenderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(RoundedEntry), typeof(RoundedEntryAndroid))]
namespace TestApp.Droid.CustomRenderers
{
    public class RoundedEntryAndroid : EntryRenderer
    {
        public RoundedEntryAndroid(Context context) : base(context)
        {
        }

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

            if (Control != null)
            {
                Control.SetBackgroundColor(global::Android.Graphics.Color.LightGreen);
            }
        }
    }
}

I've tried this and I've tried downloading the example Entry Custom Renderer from https://developer.xamarin.com/samples/xamarin-forms/customrenderers/entry/ but it still doesn't work. I get no errors or warnings, but the application won't load the page with the custom renderer on it, it will crash. I'm not sure why it is crashing, I've updated to the latest Xamarin.Forms through Nuget. Also, it works if I remove the <local1:RoundedEntry Text="Test"/>

Anyone know of a fix? Thanks!

Edit: It works when deploying it to a device but not in the LivePlayer or Forms Previewer. It is a bit annoying to not be able to see what I'm doing.


ANNOUNCING: ComboBox and Floating Label Entry for iOS and Android

$
0
0

Hey folks, just wanted to let you all know that I've open sourced my Material Entry and AutoComplete (called ComboBox) today. Take a look and use it if you like.

note: only for Android and iOS at the moment
note: Android requires an AppCompat Theme

> Install-Package xfx.controls

The repo can be found on github

<xfx:XfxEntry Placeholder="Enter your name"
              Text="{Binding Name}"
              ErrorText="{Binding NameErrorText}" />


<xfx:XfxComboBox Placeholder="Enter your email address"
                Text="{Binding EmailAddress}"
                ItemsSource="{Binding EmailSuggestions}"
                SortingAlgorithm="{Binding SortingAlgorithm}"/>
// here's an example of how to do the SortingAlgorithm
public class MyViewModel : INotifyPropertyChanged
{
    public Func<string, ICollection<string>, ICollection<string>> SortingAlgorithm { get; } = (text, values) => values
        .Where(x => x.ToLower().StartsWith(text.ToLower()))
        .OrderBy(x => x)
        .ToList();
}

OnSizeAllocated, UseSafeArea, changing layouts by orientation on iPhone X

$
0
0

We use OnSizeAllocated to drastically change our layouts between landscape and portrait modes. Having to do an update, which means I finally have to deal with the iPhone X issue. I've found a problem that I'm not sure how to work around.

Setting the page to UseSafeArea is all fine and good until OnSizeAllocated fires. Seems the width and height for OnSizeAllocated don't take into account the padding placed by UseSafeArea. Likely by design, but it means we don't have a simple way to determine the actual usable width within OnSizeAllocated. I've looked and don't see an easy way to just say if this is an iPhone X reduce the width and height by the padding amount (don't want to do it for all iOS11 phones)

Any ideas on how to deal with this? I've searched for a couple hours and been unsuccessful.

Thanks!

why cant show pdf in pdf.js in UWP?

$
0
0

Hi.
I've been using pdf.js and a weibiew render to show a pdf or word file in UWP; in Release and Debug mode if it works, but when I generate the .appxbundle and install the application, I get a damaged Access error when trying to move the file from the local storage to the assets folder of the project.

The code to save the pdf:

// create file in public folder
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile sampleFile = await storageFolder.CreateFileAsync (filename, CreationCollisionOption.ReplaceExisting);

// write sring to created file
await FileIO.WriteBytesAsync (sampleFile, bytes);

// get asets folder
StorageFolder appInstalledFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFolder assetsFolder = await appInstalledFolder.GetFolderAsync ("Assets");

// move file from public folder to assets
await sampleFile.MoveAsync (assetsFolder, filename, NameCollisionOption.ReplaceExisting);
str = sampleFile.Name;

The code for the webview route:

Control.Navigate (new Uri (string.Format ("ms-appx-web: ///Assets/pdfjs/web/viewer.html? File = {0}", string.Format ("ms-appx-web: / // Assets / {0} ", WebUtility.UrlEncode (customWebView.Uri)))));

As I mentioned before, the pdf is seen in release mode and in debugu mode, but when I install the package application it marks me the error of 'access denied'; In the capabilities of my application I have everything that has to do with storage installed in my app. I would like to know how to solve this error.

How do I set the ranking star value?

$
0
0

Guys,

I'm using a ranking stars system found on this github repo: https://github.com/nishanil/Xamarin.Forms-Samples

I would like to implement a simple function where I can set the ranking stars by giving a double value to a function (i.g. SetRanking(double value);)

Preferable I would like to bind the ranking to the viewModel property

Any thoughts?

share data between views in carouselview

$
0
0

Hello everyone!, somebody knows how can I share an object or a variable between views in a carouselview page that receive a parameter from another page?

thanks in advance!

Type Local Not Found In xmlns clr:namespace

$
0
0

Hi Team,

I am trying to implement MVVM example from your tutorial. Now when I am trying to ClockViewModel.cs access from .xaml, I am getting error

I have already tried to get solve this issue from Stackoverflow & other thread but no sucsess. Could you please help me to resolve this issue? I am working on same namespace.

Moreover, examples provided by you not working, so please also let me know from where a beginner should start.

Access list data from tapgesture from image inside viewcell

$
0
0

I have a image inside a ViewCell, I've added a TapGestureRecognizer to the image, now when the user clicks the image I want to Access the data from data ViewCell

How can I do that?

Thanks


Solution not building due to Xamarin.Forms.Build.Tasks.GetTasksAbi task not loading

$
0
0

I have just installed VS 2017 Community with the Xamarin forms add on. I tried to create a test application for Android and iOS but I cannot get it to build even without touching any of the code.
This is the error I am receiving:
_The "Xamarin.Forms.Build.Tasks.GetTasksAbi" task could not be loaded from the assembly C:\Users....nuget\packages\xamarin.forms\3.1.0.583944\build\netstandard2.0\Xamarin.Forms.Build.Tasks.dll. Could not load file or assembly 'file:///C:\Users...nuget\packages\xamarin.forms\3.1.0.583944\build\netstandard2.0\Xamarin.Forms.Build.Tasks.dll' or one of its dependencies. The system cannot find the file specified. Confirm that the declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask
_
I have tried to change the Xamarin.Forms version to a lower version but this gives the same error.
Anyone know how to get this to work?

Xamarin.Forms.Build.Tasks.GetTasksAbi" task could not be loaded

$
0
0

The "Xamarin.Forms.Build.Tasks.GetTasksAbi" task could not be loaded from the assembly C:\Users\Asus.nuget\packages\xamarin.forms\3.0.0.550146\build\netstandard2.0\Xamarin.Forms.Build.Tasks.dll. Could not load file or assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified. Confirm that the declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.

How to decrease size of apk in Xamarin forms.

$
0
0

This is my first try at release app. I am registering and logging in app via Web Api. I have a live website and have written Api Service for that. It is working fine and then i released the apk. Firstly it was of 55.5 MB then after tinkering a little bit i came up to 15 MB.
But i think that 15 MB is too large for an app that has minimal functionality.
Currently my settings are-
Generate one package - checked
Enable progurad - checked
Linking- SDK and user assemblies.

I would like to bring down the size more . Please anybody have any suggestions.

PS: Forgive if i sound naive i am new to xamarin and trying to learn it.

How to restrict numeric values entered into an Entry field.

$
0
0

I need to restrict the value being typed into an Entry field to values between 0 and 20. However, I don't want highlight it in red if it's outside that range or anything, I want to actually prevent the value from appearing in the field if the user types 30, for example (the 3 would appear since it's valid but if the user then types a 0 it should not be accepted). I have successfully used behaviors to validate things like email addresses and date formats and was wondering if I can create a behavior to do this numeric validation and if so how I would go about it? Should I interrogate the entry using the TextChanged event or something?

How to force a refresh of a page?

$
0
0

I have a page with a 'button' (actually a TapGestureRecognizer on a StackLayout). When pressed I add or remove some things from another StackLayout in the page.

The problem is that on Android after pressing sometimes you still see parts of the previous screen like duplicate buttons (1 in old location and 1 in new location). This goes away when you touch the screen and scroll it a little bit. But I want to do this refresh from code.

What I tried:

  • ForceLayout() or InvalidateMeasure() on the page after my changes
  • ForceLayout() on the ScrollView after my changes
  • Putting the layout changes in a Device.BeginInvokeOnMainThread

I 'solved' it by scrolling from code after my changes: await scrollview.ScrollToAsync(scrollview.ScrollX, scrollview.ScrollY - 1, false);

Does anyone have a better solution? Or is it a bug in Forms that its makers should solve?

Viewing all 77050 articles
Browse latest View live


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