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

is it possible in ListView to bind same property to two labels ?

$
0
0

Hello,

I just want to know if there is a way to bind same property to two different labels.

For e.g. I want this

Monday                 Tuesday
1:30 PM - 2:30 PM       3:30 PM - 4:30 PM

instead of

Monday
1:30 PM - 2:30 PM
Tuesday
3:30 PM - 4:30 PM

I tried to bind like this

<Grid>
.... // Contains a row and 3 column definition
                            <StackLayout Spacing="0" Padding="0,1"  Grid.Row="0" Grid.Column="0" >  // Monday
                              <Label  Text="{Binding day}" T/>
                              <Label  Text="{Binding time}" " />
                            </StackLayout>
                            <BoxView Grid.Row="0"  Grid.Column="1" BackgroundColor="Black"/>         // Seperator
                            <StackLayout Spacing="0" Padding="0,2" Grid.Row="0" Grid.Column="2">    // Tuesday
                              <Label Text="{Binding day}"  />
                              <Label Text="{Binding time}"  />
                            </StackLayout>
</Grid>

But it displays Monday in both the fields and then it takes separate grid for Tuesday and so on... Is there any way to display all 7 days in one grid ?

Thank you.


How to get MIME TYPE from Filename

$
0
0

Hello,

Is there an alternative to System.Web.MimeMapping.GetMimeMapping(filename).
I tried reference System.Web but I found out it is not possible.

Thank you in advance

Crossplatform way to copy a file?

$
0
0

I am using PCLStorage to figure out file paths, but I noticed it only has a FileMove and FileRename, but not a FileCopy. How can I copy / make a duplicate of a file in a different location in my PCL code?

"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))" error in PCL Storage

$
0
0

I am using PCL Storage plugin to copy a selected picture file from Pictures Library to Local Storage. I get this error in UWP only when overwriting an existing file. It works in Android and iOS. If the file already doesn't exist, there will be no problem in copying the file. The statement that is raising this exception is:

IFile destPhotoFile = await rootFolder.CreateFileAsync(copy2Filename, CreationCollisionOption.ReplaceExisting);

ImageSource To FileImageSource

$
0
0

Hi all,

I want to put an image on Button and she need a FileImageSource but i have my image in PCL. So how can i do for put my image?

It's possible to convert an ImageSource to FileImageSource?
Or an other idea for do that?

Thanks in advance.

SkiaSharp SKGLView - iOS pixel point on touch

$
0
0

Im using SKGLView in my PCL project to load an image and I need to be able to detect the pixel point on the image when the user taps on the image. I have a renderer setup and on android it works perfect, I can get the pixel point on touch. iOS however, on a touch it doesnt return the pixel point on the image, but instead it returns the touch point on the view containing the image. SkiaSharp doesnt expose the the SKGLView to use in a custom renderer so I cant go that route. Has anyone done this and can you provide guidance?

StartActivityForResult() not avaiable?

$
0
0

Hello,

i want to display the android mail app and wait for the result.
On Android this is possible with using StartActivityForResult().
But Xamarin.Forms has only Application.Context.StartActivity();
How can i start for result?

picker Title color

$
0
0

Hii how to change the title color for picker ..
in windows emulator i am not able to see the title in picker as i kept background color as white .. so title is not being visible

thankyou


ViewBox in Xamarin.Forms

$
0
0

Hello there,
I'm new to Xamarin.Forms so maybe this will be a stupid question but is there a ViewBox kind of control in Xamarin? I'm trying to transfer a WPF application to xamarin and in this application I have a canvas inside a ViewBox. This canvas is used to draw some random user controls but it's important for me that all of the controls on the canvas are visible, no matter the size of the screen. Is it possible to do something like this in xamarin.forms portable app?

Large Bitmap Custom File Loader for android (no more memory leaks)

$
0
0

There's been countless times that I've encountered memory leaks on android. 9 out of 10 times, it was because I had high resolution images in my resource folder. For example, if you have an image of 3000 x 3000, and its display resolution on screen is only 300 x 300, you would only want that 300 x 300 bitmap in the memory. Sadly, the android implementation of the image class in Xamarin.forms doesn't do that for you. So I came up with a custom image renderer that does.

Big Image class

using Xamarin.Forms;

namespace YOURPROJECTNAME
{
    public class BigImage : Image
    {
    }
}

Custom Big Image Renderer:

using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Renderscripts;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

using YOURPROJECTNAME;
using YOURPROJECTNAME.Droid;

[assembly: ExportRenderer(typeof(BigImage), typeof(BigImageRenderer))]

namespace BlurredImageTest.Droid
{
    public class BigImageRenderer : ViewRenderer<BigImage, ImageView>
    {
        private bool _isDisposed;

        public BigImageRenderer()
        {
            AutoPackage = false;
        }

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

            if (Control == null)
            {
                var imageView = new BigImageView(Context);
                SetNativeControl(imageView);
            }

            UpdateBitmap(e.OldElement);
            UpdateAspect();
        }

        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (e.PropertyName == Image.SourceProperty.PropertyName)
            {
                UpdateBitmap(null);
                return;
            }
            if (e.PropertyName == Image.AspectProperty.PropertyName)
            {
                UpdateAspect();
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (_isDisposed)
            {
                return;
            }
            _isDisposed = true;
            BitmapDrawable bitmapDrawable;
            if (disposing && Control != null && (bitmapDrawable = (Control.Drawable as BitmapDrawable)) != null)
            {
                Bitmap bitmap = bitmapDrawable.Bitmap;
                if (bitmap != null)
                {
                    bitmap.Recycle();
                    bitmap.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        private void UpdateAspect()
        {
            using (ImageView.ScaleType scaleType = ToScaleType(Element.Aspect))
            {
                Control.SetScaleType(scaleType);
            }
        }

        private static ImageView.ScaleType ToScaleType(Aspect aspect)
        {
            switch (aspect)
            {
                case Aspect.AspectFill:
                    return ImageView.ScaleType.CenterCrop;
                case Aspect.Fill:
                    return ImageView.ScaleType.FitXy;
            }
            return ImageView.ScaleType.FitCenter;
        }

        private async void UpdateBitmap(Image previous = null)
        {
            Bitmap bitmap = null;
            ImageSource source = Element.Source;
            if (previous == null || !object.Equals(previous.Source, Element.Source))
            {
                SetIsLoading(true);
                ((BigImageView)base.Control).SkipInvalidate();

                Control.SetImageResource(global::Android.Resource.Color.Transparent);
                if (source != null)
                {
                    try
                    {
                        bitmap = await GetImageFromImageSource(source, Context);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    catch (IOException)
                    {
                    }
                    catch (NotImplementedException)
                    {
                    }
                }
                if (Element != null && object.Equals(Element.Source, source))
                {
                    if (!_isDisposed)
                    {
                        Control.SetImageBitmap(bitmap);
                        if (bitmap != null)
                        {
                            bitmap.Dispose();
                        }
                        SetIsLoading(false);
                        ((IVisualElementController)base.Element).NativeSizeChanged();
                    }
                }
            }
        }

        private async Task<Bitmap> GetImageFromImageSource(ImageSource imageSource, Context context)
        {
            IImageSourceHandler handler;

            if (imageSource is FileImageSource)
            {
                int width = -1, height = -1;

                if ((int)((Image)Element).Width != -1)
                    width = (int)((Image)Element).Width;
                else if ((int)((Image)Element).WidthRequest != -1)
                    width = (int)((Image)Element).WidthRequest;

                if ((int)((Image)Element).Height != -1)
                    height = (int)((Image)Element).Height;
                else if ((int)((Image)Element).HeightRequest != -1)
                    height = (int)((Image)Element).HeightRequest;

                handler = new CustomFileImageSourceHandler { reqWidth = width, reqHeight = height };
            }
            else if (imageSource is StreamImageSource)
            {
                handler = new StreamImagesourceHandler(); // sic
            }
            else if (imageSource is UriImageSource)
            {
                handler = new ImageLoaderSourceHandler(); // sic
            }
            else
            {
                throw new NotImplementedException();
            }

            var originalBitmap = await handler.LoadImageAsync(imageSource, context);

            return originalBitmap;
        }

        private class BigImageView : ImageView
        {
            private bool _skipInvalidate;

            public BigImageView(Context context) : base(context)
            {
            }

            public override void Invalidate ()
            {
                if (this._skipInvalidate) {
                    this._skipInvalidate = false;
                    return;
                }
                base.Invalidate ();
            }

            public void SkipInvalidate ()
            {
                this._skipInvalidate = true;
            }
        }

        private static FieldInfo _isLoadingPropertyKeyFieldInfo;

        private static FieldInfo IsLoadingPropertyKeyFieldInfo
        {
            get
            {
                if (_isLoadingPropertyKeyFieldInfo == null)
                {
                    _isLoadingPropertyKeyFieldInfo = typeof(Image).GetField("IsLoadingPropertyKey", BindingFlags.Static | BindingFlags.NonPublic);
                }
                return _isLoadingPropertyKeyFieldInfo;
            }
        }

        private void SetIsLoading(bool value)
        {
            var fieldInfo = IsLoadingPropertyKeyFieldInfo;
            ((IElementController)base.Element).SetValueFromRenderer((BindablePropertyKey)fieldInfo.GetValue(null), value);
        }
    }
}

Custom file Image loader:

using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using Android.Graphics;
using Android.Content;
using Xamarin.Forms.Platform.Android;

namespace YOURPROJECTNAME.Droid
{
    public class CustomFileImageSourceHandler : IImageSourceHandler
    {
        public int reqWidth;
        public int reqHeight;

        public async Task<Bitmap> LoadImageAsync(ImageSource imagesource, Context context, CancellationToken cancelationToken = default(CancellationToken))
        {
            var imageLoader = imagesource as FileImageSource;
            if (imageLoader != null && imageLoader.File != null)
            {
                if (reqWidth != -1 && reqHeight != -1)
                {
                    int resID = GetImageResourceID(imageLoader.File);
                    BitmapFactory.Options options = await GetBitmapOptionsOfImage(resID);
                    return await LoadScaledDownBitmapForDisplayAsync(resID, options, reqWidth, reqHeight);
                }
                else
                {
                    var handler = new FileImageSourceHandler();
                    return await handler.LoadImageAsync(imagesource, context, cancelationToken);
                }
            }
            return null;
        }

        int GetImageResourceID(string fileName)
        {
            fileName = fileName.Replace(".png", "").Replace(".jpg", "");
            var resField = typeof(Resource.Drawable).GetField(fileName);
            var resID = (int)resField.GetValue(null);
            return resID;
        }

        int CalculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
        {
            // Raw height and width of image
            float height = options.OutHeight;
            float width = options.OutWidth;
            double inSampleSize = 1D;

            if (height > reqHeight || width > reqWidth)
            {
                int halfHeight = (int)(height / 2);
                int halfWidth = (int)(width / 2);

                // Calculate a inSampleSize that is a power of 2 - the decoder will use a value that is a power of two anyway.
                while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth)
                {
                    inSampleSize *= 2;
                }
            }

            return (int)inSampleSize;
        }

        async Task<BitmapFactory.Options> GetBitmapOptionsOfImage(int resID)
        {
            BitmapFactory.Options options = new BitmapFactory.Options
            {
                InJustDecodeBounds = true
            };

            // The result will be null because InJustDecodeBounds == true.
            Bitmap result = await BitmapFactory.DecodeResourceAsync(Forms.Context.Resources, resID, options);

            int imageHeight = options.OutHeight;
            int imageWidth = options.OutWidth;

            //_originalDimensions.Text = string.Format("Original Size= {0}x{1}", imageWidth, imageHeight);

            return options;
        }

        async Task<Bitmap> LoadScaledDownBitmapForDisplayAsync(int resID, BitmapFactory.Options options, int reqWidth, int reqHeight)
        {
            // Calculate inSampleSize
            options.InSampleSize = CalculateInSampleSize(options, reqWidth, reqHeight);

            // Decode bitmap with inSampleSize set
            options.InJustDecodeBounds = false;

            return await BitmapFactory.DecodeResourceAsync(Forms.Context.Resources, resID, options);
        }
    }
}

My solution is inspired by the following posts:
http://blog.adamkemp.com/2015/05/blurred-image-renderer-for-xamarinforms.html
https://developer.xamarin.com/recipes/android/resources/general/load_large_bitmaps_efficiently/

BetterSlider and BetterStepper - Data Bindable Controls done right!

$
0
0

I've gotten so frustrated wrestling with exceptions caused by the "unfriendly" implementation of Slider and Stepper data binding that I've fixed them! The problem is that combinations of properties that would result in the control having nothing to do raise exceptions. With data binding it is hard to control the order in which properties get set, so invalid combinations can easily occur fleetingly when the control range is being reset. Furthermore for a dynamic range situations where there is nothing to do occur naturally and you just want the control disabled in this case. Doing that at the moment involves yet more intricate data binding to the IsEnabled property.

The code below inherits the Stepper Control and specialises it to fix these problems. The control is automatically disabled when the range is invalid and the value is automatically kept within the range:

public class BetterStepper : Stepper
{
    public BetterStepper() : base() {}
    public new double Minimum
    {
        get { return (double)GetValue(MinimumProperty); }
        set { SetValue(MinimumProperty, value); }
    }
    public static new BindableProperty MinimumProperty = BindableProperty.Create(nameof(MinimumProperty),
        typeof(double), typeof(BetterStepper), (double)0, defaultBindingMode: BindingMode.OneWay, propertyChanged: OnPropertyChanged);
    public new double Maximum
    {
        get { return (double)GetValue(MaximumProperty); }
        set { SetValue(MaximumProperty, value); }
    }
    public static new BindableProperty MaximumProperty = BindableProperty.Create(nameof(MaximumProperty),
        typeof(double), typeof(BetterStepper), (double)1, defaultBindingMode: BindingMode.OneWay, propertyChanged: OnPropertyChanged);
    public new double Increment
    {
        get { return (double)GetValue(IncrementProperty); }
        set { SetValue(IncrementProperty, value); }
    }
    public static new BindableProperty IncrementProperty = BindableProperty.Create(nameof(IncrementProperty),
        typeof(double), typeof(BetterStepper), (double)1, defaultBindingMode: BindingMode.OneWay, propertyChanged: OnPropertyChanged);
    public new bool IsEnabled
    {
        get { return (bool)GetValue(IsEnabledProperty); }
        set { SetValue(IsEnabledProperty, value); }
    }
    public static new BindableProperty IsEnabledProperty = BindableProperty.Create(nameof(IsEnabledProperty),
        typeof(bool), typeof(BetterStepper), true, defaultBindingMode: BindingMode.OneWay,
        propertyChanged: OnPropertyChanged);
    private static void OnPropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
        (bindable as BetterStepper).LimitsChanged();
    }
    private void LimitsChanged()
    {
        bool ok =  (Maximum >= (Minimum + Increment));
        base.IsEnabled = IsEnabled && ok;
        if (!ok) return;
        base.Increment = double.Epsilon; // temporarily set increment as small as possible to avoid possible exception.
        if (Value > Maximum) Value = Maximum;
        base.Maximum = Maximum;
        if (Value < Minimum) Value = Minimum;
        base.Minimum = Minimum;
        base.Increment = Increment;
    }
}

Any criticisms/improvements welcome. If there is any interest I'll publish BetterSlider too, but that is more complex as it adds some functionality like the ability to reverse the range and an Increment property.

In my view the Xamarin implementations ought to work this way out of the box, as I can see no real downside.

Caveat: I've only tested this on the Android platform, but there is no reason it should not work on other platforms.

Strange behaviour with ToolBarButton in Xamarin.Forms.UWP

$
0
0

The following code in a ContentPage adds a button in the top-right corner of XF-Android and XF-IOS App:

var mnuMainOptions = new ToolbarItem
            {
                Text = "Menu",
                Icon = HelperXF.IconFileName("more"),
                Order = ToolbarItemOrder.Primary   ,
            };
            mnuMainOptions.Clicked += mnuMainOptions_Clicked;
            this.ToolbarItems.Add(mnuMainOptions);

But in XF-UWP it creates two buttons, one with the Icon and one with Text. Only when I click on the second one with the text, the clicked-event is fired. Bug or feature of UWP?

Apple rejected XForms app

$
0
0

Apple rejected my Xamarin.Forms application for the following reasons:

This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSContactsUsageDescription key with a string value explaining to the user how the app uses this data.
This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSCalendarsUsageDescription key with a string value explaining to the user how the app uses this data.
This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSMicrophoneUsageDescription key with a string value explaining to the user how the app uses this data.
This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSAppleMusicUsageDescription key with a string value explaining to the user how the app uses this data.
This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSSiriUsageDescription key with a string value explaining to the user how the app uses this data.
Once these issues have been corrected, you can then redeliver the corrected binary.

The problem is that I'm not using any of those features and therefore have not included the NSblah descriptions in my Info.plist. Is there something special that I need to do for Xamarain.Forms projects that target iOS 10?

Thanks!

Xamarin.Forms Previewer not working for Android?

$
0
0

I am working in VS 2015 with a mac-mini build server, XF 2.3.2.127, Xamarin for Visual Studio is up-to-date in the stable channel (v4.2)
I built a test app with sample data as prescribed by this awesome post by James Montemagno. The app has both run-time and design-time data. It all compiles, deploys and runs on iOS, android devices and UWP with no problems.
The iOS preview seems to be working wonderfully. It updates immediately when the XAML is updated. It is awesome - seriously one of the best things I have ever laid eyes on. :-)

I can't get the Android previewer to work. I have updated all of the Android SDKs to the latest.

I have tried all kinds of combinations of the following:
Compile using Android Version: Latest 24 or 23
Minimum Android to target: API level 24 or 23
Target Android Version: API Level 24 or 23

Sometimes I get:
"The Android project needs to be build before preview can be created" - the project is cleaned, built successfully, runs fine, etc.
sometimes I get:
"XFPageRendererView"
sometimes I get:
"Invalid XAML: The project has been closed." - this one really doesn't make any sense.

screen cap 1
screencap2
screencap3

Any help would be appreciated!

Master detail page strange behavior after update

$
0
0

Hi,

Since I updated Xamarin Forms to latest version (2.3.2.127), the detail pages (which are navigation pages) from my master detail, flicker.
Each time I select a different page, the navigation bar disappears and then reappears.
Although when I use PushAsync, the navigationbar stays in place and only the title changes.
Does anyone know how to fix this?


How to build Xamarin Forms App with Linker enabled and resolved dependency?

$
0
0

I've developed many Xamarin Forms Apps but this time I'm getting a big issues as I'm not able to reduce the size of the app. I've integrated many other nuget packages and sdk like onesignal for push notifications, Amazon AWS S3 for files upload and show etc. The problem is, When I integrate the SDK in a test app then it successfully builds and all done but in my main project I'm having error. In Android, Onesignal shows error and so when I disable linker then it works and in iOS Amazon S3 SDK shows error and when I disable linker then it works fine. But the size of the app increases too much and which is not acceptable. I've also tried skipping the assemblies option but that again don't work. :(

How can I resolve this problem?

ScrollView inside scrollview?

$
0
0

I am trying to create an instant messaging app, similar to Messages on iOS. So I have

<StackLayout>
    <ScrollView x:Name="ScrollViewMessages" VerticalOptions="FillAndExpand">
        <StackLayout x:Name="StackLayoutMessages" VerticalOptions="FillAndExpand">
            <StackLayout Padding="20,0,0,0">
                <Editor Text="This is a test from the sender." BackgroundColor="#9ec7f5" IsEnabled="false" />
            </StackLayout>
            <StackLayout Padding="0,0,20,0">
                <Editor Text="This is a test from the receiver." BackgroundColor="#d9d9d9" IsEnabled="false" />
            </StackLayout>
        </StackLayout>
    </ScrollView>
    <Editor BackgroundColor="Black" />
</StackLayout>

for my basic layout. However, I keep running into issues when I use the entry. The iOS keyboard covers it up. When I put everything into a scrollview, it ruins the scrollview for the messaging. I have attached images for clarity.

How to implement a image in accordion menu?

$
0
0

Hello everyone,
I would like to know how I can implement an image within the contents of the accordion menu, I already got a string data, because I am consuming a service of a Json, but I want it inside the contents of the accordion menu, either:
Image-label-image.

And I throw this error: System.NullReferenceException: Object reference not set to an instance of an object.

But I can not appear if I want an image, I was reading several articles on this case but I have not found a solution, this is my code.

public List GetSampleData()
{

        var vResult = new List<AccordionSource>();



        userPathContract = Application.Current.Properties["UserTrail"] as UserPathContract;



        foreach (var skill in userPathContract.Skills)
        {
            ListView listViewYes = new ListView

            {

                ItemTemplate = new DataTemplate(typeof(TextCell))

            };


            listViewYes.ItemTemplate.SetBinding(TextCell.TextProperty, "Name");


            listViewYes.ItemsSource = userPathContract.Requisites.Where(r => r.SkillId == skill.Id);
            listViewYes.ItemTapped += OnTap1;

            var accordionTap = new AccordionSource()
            {
                HeaderText = skill.Name,
                HeaderTextColor = Color.White,
                HeaderBackGroundColor = Color.FromHex("#1F549D"),
                ContentItems = new StackLayout()
                {
                    Orientation = StackOrientation.Horizontal,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    Children =
                    {
                       listViewYes
                    }

                }
            };
            vResult.Add(accordionTap);
        }

        return vResult;

    }

Capture Photos/Videos from Camera (Custom Render) Tap/Long press

$
0
0

Hi all,

I already have a Camera custom render very similar to this CameraProvier where I can take Photos without any problem, the thing is that now I need to record video using the same View or Camera, I mean, when I Tap over the camera it should take a Photo, but if I long press it should record a video,

does anybody knows how can I Implement this kind of events in the Camera, or the other scenario is to have another button to record a video (Overlay)

I will really appreciate if someone can point me in the right direction on this,

thank you all!

Bug with the Picker control on Xamarin Forms?

$
0
0

I am working right now with Xamarin Forms and testing with Android. It seems that the Picker Control has problems, I don't know if I did something wrong, when you are going to pick an item, the style appears so weird (no background and some elements missing). Here is an screenshot:

http://grab.by/L9xS

Any idea what is happening? I am not using custom render neither an special style for the control (just theming options for material support (which is the @JamesMontemagno 's guide))

I am working on Visual Studio 2015, latest beta update and using Visual Studio Emulator for Android (I have tested this on Android 4.4 and 5.0)

Thanks in advance!

Viewing all 91519 articles
Browse latest View live


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