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

Xamarin Shell ToolBarItem Image from storage

$
0
0

Hi,

I am a newbie at Xamarin…. So I would appreciate any help…

My app allows a user to select a profile picture - using instructions from:
ttps://lalorosas.com/blog/xamarin-forms-selecting-image-from-the-gallery

My app then saves the image and is able to reload the image into an ImageButton successfully using:
ttps://stackoverflow.com/questions/51038251/how-to-download-image-and-save-it-in-local-storage-using-xamarin-forms

I want to be able to reload the image from the database and put the image into the SHELL 
TOOLBARITEM and I haven’t been able to find instructions on that.

Can someone point me in the right direction.


ListView binding to ObservableCollection does not update GUI

$
0
0

Hi

Can anyone tell me why this simple code is not working as expected? Does the ListView control not listen for changes in the bound property?

  • Expected: when I click the Add button, the GUI (ListView) updates through the binding and shows the new element in the ObservableCollection.
  • Observed: GUI does not update but always shows the initial three items of the ObservableCollection.
  • Btw: OnAddButtonClicked() does get called and ListViewItems does get updated (checked in the debugger). Calling OnPropertyChanged("ListViewItems") inside OnAddButtonClicked() did not help either.
  • And: if I update the code as follows, the ListView works: add a Label control, bind that label to a 2nd property, update that property inside OnAddButtonClicked(), call OnPropertyChanged() from inside the property setter. So obviously this call to OnPropertyChanged() somehow triggers the ListView to get updated as well...
  • I'm now using Xamarin.Forms version 1.1.0.6201. Didn't work with the previous version either.

XAML:

<?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="Test1.MainPage"
             Padding="10" Title="MainPageXaml">
    <StackLayout VerticalOptions="StartAndExpand" HorizontalOptions="Fill">
        <Button Text="Add" Clicked="OnAddButtonClicked" />
        <ListView ItemsSource="{Binding ListViewItems}" />
    </StackLayout>
</ContentPage>

C#:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        ListViewItems = new ObservableCollection<string> { "one", "two", "three" };
        BindingContext = this;
    }

    private void OnAddButtonClicked(object sender, EventArgs e)
    {
        ListViewItems.Add(DateTime.Now.ToString());
        // OnPropertyChanged("ListViewItems");
    }

    public ObservableCollection<string> ListViewItems { get; set; }
}

Markus

CollectionView.Footer

$
0
0

Hello,

My code:

<CollectionView SelectionMode="Single" ItemSizingStrategy="MeasureFirstItem" ItemsSource="{Binding ItemInfo}" 
                  SelectedItem="{Binding SelectedItemInfo}"
                  RemainingItemsThreshold="{Binding ItemTreshold}" 
                  RemainingItemsThresholdReachedCommand="{Binding LoadMoreItemInfoCommand}">

            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid Style="{StaticResource gridGeneral}">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <ffimageloading:CachedImage Grid.RowSpan="1" HorizontalOptions="CenterAndExpand" 
                                            VerticalOptions="CenterAndExpand" Aspect="AspectFill"
                                            WidthRequest="54" HeightRequest="54" 
                                            DownsampleToViewSize="true"
                                            Source="{Binding Photo}">
                            <ffimageloading:CachedImage.Transformations>
                                <fftransformations:CircleTransformation BorderSize="5" BorderHexColor="#000000" />
                            </ffimageloading:CachedImage.Transformations>
                        </ffimageloading:CachedImage>
                        <Label Style="{StaticResource labelList}" Text="{Binding Name}" Grid.Column="1" />
                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>

            <CollectionView.Behaviors>
                <b:EventToCommandBehavior EventName="SelectionChanged" Command="{Binding NavigateItemCommand}" />
            </CollectionView.Behaviors>

            <CollectionView.Footer>
                <ActivityIndicator IsRunning="{Binding Loading}"
                           Color="{StaticResource redGeneralColor}"
                           HorizontalOptions="Center"
                           VerticalOptions="EndAndExpand" />
            </CollectionView.Footer>

        </CollectionView>

I don't understand why LoadMoreItemInfoCommand runs at the beginning.

And ActivityIndicatornot showing.

ItemInfo is an ObservableCollectionthat is initialized in the ViewModelconstructor

Free UI Kits for Xaml

$
0
0

Is their any good free ui kits out their for xaml wanting to create a nice home page for my app but my design skills are lacking.

How do I set the font family of a label, platform to platform.

$
0
0

I'm a beginner in Xamarin and xml. I know a some C#. I'm trying to set the font of my Xamarin Forms application on the android version specifically, that way I can get a monospace font (Droid Sans Mono). I've looked around at a lot of threads about fonts and OnPlatform and data bindings, but I'm a little bit lost. I'm pretty sure Font.FontFamily is read-only as well.

here are some examples of things I have tried:
Label1.FontFamily = Device.OnPlatform("MarkerFelt-Thin", "Droid Sans Mono", "Comic Sans MS");

<Label x:Name="Label1" Text="" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"> <Label.FontFamily> <OnPlatform x:TypeArguments="String"> <On Platform="Android">Droid Sans Mono</On> </OnPlatform> </Label.FontFamily> </Label>

Change Image Source in Code in Xamarin Forms

$
0
0

I have an Image that is too small for Tablets so i need to change it with another Image in Code
and i found that i can write this :

c# :

HeaderImg.Source = "locationPng.png";

but i see no one is doing this because it is a **bad practice ** !
Why is it a bad practice and what is the right way to change Image Source in Code ? Or is it a good solution ?

my Xaml :

** Image x:Name="HeaderImg" Source="LogoBG012" Grid.Row="0" **

my C# :

if (Device.Idiom == TargetIdiom.Tablet)
{
// Code needed
}
else if (Device.Idiom == TargetIdiom.Phone)
{
HeaderImg.Aspect = Aspect.AspectFit;
}

eliteKit: Xamarin Forms UI Kit

$
0
0

Hi guys,

I'm proud to announce the first release of the eliteKit Xamarin Forms UI Kit. It's a collection of 20 UI elements made with SkiaSharp to make it much easier creating and design your next app.

You can find all informations about this project under www.eliteKit.de.

A free LITE version is available with 10 UI elements. There is also a PRO version containing all 20 UI elements. We're planning to create a lot of more UI elements in future, as we're a team of 3 people creating, developing and designing awesome elements. Lifetime updates are for free available.

With a built in community you can ask any questions related to eliteKit to staffs or other community members. We're giving our best to answer and help you immediately or as fast as possible. You can even ask us to create new UI elements or suggest us any changes to existing elements. For any found bug's we'd be happy to get noticed about it in the eliteKit bug reports category.

Feel free to have a look on our homepage under www.eliteKit.de

How can I show a notification? (popup) like facebook, whatsapp, spotify daoes it

$
0
0

At the same way spotify, facebook, whatsapp, instagram show you a notification (popup) when you recive a message, I need to show a message in my app even if this it is off. Any idea?


How to create Linear reveal animation in xamarin form?

$
0
0

Hi, i want to create linear reveal animation in xamairn form, i have reference of circle reveal animation source code but need to convert into linear reveal animation. I have tried but field any one please help me.

Circle reveal animation layout source code reference: https://github.com/mariusmuntean/FormsRevealer

Place Image on Frame's Border

$
0
0

Hi,

How can I place an image on the Frame border centered just like the Bill gates and USA flag here in the attached image?

Thanks,
Jassim

Selecting a StackLayout in a ListView is very difficult - How can it be made easier?

$
0
0

The DataTemplate of my ListView contains a StackLayout. That StackLayout has a few child views. Labels, Entrys, DateTimePickers, etc. I would expect a single or double tap anywhere in rectangular bounds of the StackLayout to actually "highlight" the entire StackLayout. However, it only happens if I tap in an area above or below my other view controls (is that the appropriate term?) in the StackLayout. How can I get the StackLayout to highlight everything even when tapping on the child views?

The only way I can think of at the moment is to set tap handlers (GestureRecognizers) on all the child controls that would have a single line of code to set the ListView's SelectedItem property to the parent StackLayout. Is that the best solution here?

Xamarin forms: How to parse HTML Data having video links?

$
0
0

I have video links(Vimeo video) and normal texts in my HTML data. I am using Xam.Plugin.HtmlLabel for parsing the HTML data. But it is not effective, the links are not clickable on the iPhone. Also, the video links are missing when coming to UI.

I have added my sample HTML data here. I am using a webview for showing videos. So the video links should open on the app itself using webview or any other property. And show the remaining description as normal text. I need a UI like this. How can I do this? My current UI using Xam.Plugin.HtmlLabel.

App freezes on iPad when in split view mode (multi-tasking) and change between pages

$
0
0

I have come across a very strange bug -- not sure if it in my app, Xamarin.Forms, or iOS itself.

My app switches between several pages derived from ContentPage. When I have my app and another app, for example the iOS "Pages" app on my iPad side-by-side (half screen). It seems to be related to whether the other app is in an input field before switching. Anyway, I press a Button in my app to switch to another page, and my page is kinda there, but the dark blue background want is white, plus no interaction (so, appears "frozen"). But, if move the slider to make it a 2/3 split, it immediately works.

When my app starts in 2/3 screen mode, the result is a bit comical -- the first half of my app is OK (the leftmost third of the screen), but other half refuses to allow interaction (and has white background). Weirdest thing -- one of my buttons straddles the break -- the left part works fine, the right does not.

I've not seen this on an iPad that has not updated to 13.x yet. I'm suspcious that this might be the same issue or related to White Screen after navigating to MasterDetailPage on iPAD iOS 13.2 and iOS 13.0 Broke MasterDetailPage on iPads?, so I added tags that might relate. But, here's the thing -- I'm currently using XF 4.3 (4.3.0.991221). The "solution" for the others was to update to 4.3. And, I'm not really using MasterDetailPage, and those issues don't mention SplitScreen.

I'd just like to hear if someone else has seen something like this, or has any quick suggestions before I try to create a simplified example.

Xamarin, how can i access a specific column property in sqlite so i can add the values?

$
0
0

I know how to read or show all data inserted in the database but I don't know how to query a specific data. In the my database is in Post.cs it will store date/time and get 2 datas from user.
so like this: enter image description here

Column1(ID), Column2(Date), (column3(rain1), column4(rain2).
1 12/13/2019 21 22
2 12/16/2019 21 22
3 12/16/2019 11 12
I want to do: if (rain1 && rain2) have the same date. I would like to add 2data from rain1 which is 21+11 and save the total to rain1total=32 then rain2total would be 34. I don't know where to start

here is Post.cs

namespace listtoPDF.Model
{
//Post table, user posting drainvolume
//this is the source of Binding
public class Post: INotifyPropertyChanged
{
private double? rain1Vol;
private double? rain2Vol;
//from settingspage to show up in history
string rain1lbl = Settings.Drain1LocationSettings;
string rain2lbl = Settings.Drain2LocationSettings;

//ID primary key that we will autoincrement
//These are columns ID, drain1 to 8 so 9 columns
//These are binding source for Historypage
[PrimaryKey, AutoIncrement]
public int ID { get; set; }

public static bool showLabel { get; set; }  //public class model

public string rain1Lbl
{
    get => rain1lbl;
    set => rain1lbl= Settings.Drain1LocationSettings;    
}

public string rain2Lbl
{
    get => rain2lbl;
    set => rain2lbl= Settings.Drain2LocationSettings;    
}

public string CDateTime { get; set; }

[MaxLength(3)]
public double? rain1vol
{
    get { return rain1Vol; }
    set
    {
        rain1Vol = value;
        RaisePropertyChanged("rain1vol");
    }
}
[MaxLength(3)]
public double? rain2vol
{
    get { return rain2Vol; }
    set
    {
        rain2Vol = value;
        RaisePropertyChanged("rain2vol");
    }
}
public event PropertyChangedEventHandler PropertyChanged;

void RaisePropertyChanged(string property)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(property));
    }

}

}
}
here is the main that will list data entered with date

namespace listtoPDF
{
public partial class MainPage : ContentPage
{
List posts;

public MainPage()
{
    InitializeComponent();
}

protected override void OnAppearing()
{
    base.OnAppearing();
    SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation);
    conn.CreateTable<Post>();
    posts = conn.Table<Post>().ToList();
    postListView.ItemsSource = posts;     
    conn.Close();
        //right click quickwatch

}
void addbuttonHandle_Clicked(object sender, EventArgs args)
{
    Navigation.PushModalAsync(new AddRainsPage());

}

private void GetValues()
{
    //Initiate SQLite connection
    //Create table with class
    //Get the values in table
    //close the line
    SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation);
    conn.CreateTable<Post>();
    posts = conn.Table<Post>().ToList();
    conn.Close();
}       

}
Here is the page where i need query the add a certain column so i can add the data associated to it. So far it's connecting to the sqlite.

namespace listtoPDF
{
public partial class selecteddataPage : ContentPage
{
List posts;

public selecteddataPage()
{
    InitializeComponent();
}

private void GetValues()
{
    //Initiate SQLite connection
    //Create table with class
    //Get the values in table
    //close the line
    SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation);
    conn.CreateTable<Post>();
    posts = conn.Table<Post>().ToList();

    **if (Post.rain1 values have the same date )
      {
         totalrain1= then add data that have same date         
      }
     if (Post.rain2 values have the same date )
      {
         totalrain1= then add data that have same date         
      }**

    conn.Close();

}

}
}

Frequent ApplicationMessageReceived += event from MQTTnet library causes Xamarin app to crash

$
0
0

Hi!

I've been working with Xamarin the past couple days, and this is my first big side project! I'm using the MQTTnet library to connect my mobile devices to a robotic system, to move the robot and also collect data.

The issue i'm having is with the ApplicationMessageReceived event from the MQTTnet:

client.ApplicationMessageReceived += (s, e) =>{ StatusLabel.Text = Encoding.UTF8.GetString(e.ApplicationMessage.Payload) }

On the robot side it is publishing position values at about a 200ms interval over MQTT; after about 5 seconds of the app running the subscription event, it will lock and crash. This is not the case with my C# WPF and my .Net Core versions of a similar app. I can bump the interval to about 1 second interval, and it's somewhat stable, but not ideal for position readout.

Could someone give me pointers as to what might be happening, or the cause?

I have a task setup in my main program body:

        protected override void OnCreate()
        {
            base.OnCreate();
            LoadApplication(new App());

            //Task to run MQTT
        Task.Run(async () => { await App.RunAsync(); }).Wait();
        }

        static void Main(string[] args)
        {
            var app = new Program();
            global::Xamarin.Forms.Platform.Tizen.Forms.Init(app);
            Tizen.Wearable.CircularUI.Forms.Renderer.FormsCircularUI.Init();
            app.Run(args);
        }

And then in my App I have a RunAsync that does the connection and messaging, I've cut it short for readability:

        public static async Task RunAsync()
        {
                try
                {
                    // Event Handler to the ApplicationMessageRecevied event
                    client.ApplicationMessageReceived += (s, e) =>
                    {
                        StatusLabel.Text = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                    };

                    client.Connected += async (s, e) =>
                    {
                        await client.SubscribeAsync(new TopicFilterBuilder().WithTopic(MQTTSubTopic).Build());
                        StatusLabel.Text = "Connected";
                    };

                    // Attempt a connection to the broker
                    try
                    {
                        await client.ConnectAsync(clientOptions);
                    }
                    catch
                    {
                        PositionData.Text = "Failed";
                    }
                }
                catch
                {
                    StatusLabel.Text = "Failed";
                }

        }

At this point, I'm open to try anything :smile:

I've tried moving the Task.Run() to the OnStart() event as well, and no difference in results. My .Net Core application does have a Thread.Sleep(Timeout.Infinite) directly after the Task.Run(), but adding that to this application just prevents it from launching.

Thanks!!


xamarin forms collectionView scroll height?

$
0
0

How can we measure collectionView scroll height in xamarin forms?

Detect CollectionView row Item is Appeared?

$
0
0

Hi all,

Im trying to figuire out how I can trigger event for row appearing on CollectionView, previously I used ListView.ItemAppearing Event on listview but CollectionView does not have this event unfortunately :neutral: so I need another way of detecting a row has appeared? I was using the Scrolled Event but it didnt quite achieve what I wanted since when the collectionview first displays there is no trigger fired, only when I actually scroll and not when items/rows first appear.

Basically I have a chat listview and when a row/message appears a http request sends to mark the message as seen so I rely on a trigger when row appears (user seen message) and not just scroll event.

Ive gottten this working on android but not on iOS, below on my view (actually an expandableView) i add effect with an event Appeared for view appearing:

<expandable:ExpandableView
                    ExpandAnimationLength="125"
                    Spacing="0">
                    <expandable:ExpandableView.Effects>
                        <effects:ViewLifecycleEffect Appeared="viewLifecycleEffect_AppearedAsync" />
                    </expandable:ExpandableView.Effects>
                    <expandable:ExpandableView.PrimaryView>
...

The effect in the shared project:

public class ViewLifecycleEffect : RoutingEffect
    {
        public const string EffectGroupName = "XFLifecycle";
        public const string EffectName = "LifecycleEffect";

        public event EventHandler<EventArgs>? Appeared;
        public event EventHandler<EventArgs>? Disappeared;


        public ViewLifecycleEffect() : base($"{EffectGroupName}.{EffectName}") { }

        public void RaiseAppeared(Element element)
        {
            Appeared?.Invoke(element, EventArgs.Empty);
        }

        public void RaiseDisappeared(Element element) => Disappeared?.Invoke(element, EventArgs.Empty);
    }

So finally in the iOS project I try to get notified when view is appearing/showing on screen/window but doesnt get called as views appear which should trigger per row as user scrolling:

public class IosLifecycleEffect : PlatformEffect
    {
        private const NSKeyValueObservingOptions _observingOptions = NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.OldNew | NSKeyValueObservingOptions.Prior;

        private ViewLifecycleEffect _viewLifecycleEffect;
        private IDisposable _isLoadedObserverDisposable;

        protected override void OnAttached()
        {
            _viewLifecycleEffect = Element.Effects.OfType<ViewLifecycleEffect>().FirstOrDefault();

            UIView nativeView = Control ?? Container;

            _isLoadedObserverDisposable = nativeView?.AddObserver("superview", _observingOptions, isViewLoadedObserver);

            CGRect viewBounds = nativeView.Bounds;
            CGRect windowBounds = UIScreen.MainScreen.Bounds;

    // Dont think I need this, but only checks if window on screen.
            if (windowBounds.Contains(nativeView.ConvertRectToView(viewBounds, nativeView.Window)))
            {
                _viewLifecycleEffect?.RaiseAppeared(Element);
            }
        }

        protected override void OnDetached()
        {
            _viewLifecycleEffect.RaiseDisappeared(Element);
            _isLoadedObserverDisposable.Dispose();
        }

        private void isViewLoadedObserver(NSObservedChange nsObservedChange)
        {
            _viewLifecycleEffect?.RaiseAppeared(Element);
        }
    }

Maybe there is a better way then detecting on the View or perhaps on the CollectionView itself?

Maps Works in RELEASE, DEBUG but not when in Production

$
0
0

Hi devs,

this is not my first App deployed to the Store using Xamarin.Forms, so i have experience.
I've signed and done everything regarding my Key and Maps API like I always do, but this is the First time that MAPS won't work in Production.

I signed my App using Visual Studio and deployed it, I used the SHA1 private Key and got my MAPS API Key.
I checked everything (Package name, SHA1).

Release Builds on test devices works as expected.
Debug Builds on test devices works as expected.
Production Release in Play Store doesn't Work.

Don't know what I'm missing here.

Xamarin Forms 4.3 Shell Search Handler how to disable query clear on complete

$
0
0

Hi!

I'm trying to integrate an app with the new Shell from Xamarin Forms 4.x. I'm using the latest 4.3 version (4.3.0.947036).

My issue is, when I tap the Enter button on the keyboard of the new SearchHandler that comes with Shell, the text on the searchbar automatically clears. I can't find a place where I can override or disable this behavior. I'm using a search per character inserted feature that I've created on a custom SearchHandler class, and when the search bar clears the search happens again with no characters (which I don't want).

Do you know any specific method or event that I can override or disable to avoid this "clear" behavior?

Azure B2C returning null for accesstoken

$
0
0

docs.microsoft.com/en-us/samples/azure-samples/active-directory-b2c-xamarin-native/integrate-azure-ad-b2c-xamarin-forms/

I am working on a xamarin forms app for ios and android. Using the above sample as a reference for integrating my app to azure b2c. I am getting logged in however the result is returning a "" string for the accesstoken. I appear to be getting an idtoken that looks legit. Can you point me in the right direction to resolve this issue.

Thanks
Brady

async void OnLoginButtonClicked(object sender, EventArgs e)
{
AuthenticationResult result;
try
{
result = await App.AuthenticationClient
.AcquireTokenInteractive(Constants.Scopes)
.WithPrompt(Prompt.SelectAccount)

                .WithParentActivityOrWindow(App.UIParent)
                .ExecuteAsync();
            Analytics.TrackEvent("accesstoken:" + result.AccessToken + " idtoken:" + result.IdToken);

            //await Navigation.PushAsync(new LogoutPage(result));
        }
        catch (MsalException ex)
        {
            if (ex.Message != null && ex.Message.Contains("AADB2C90118"))
            {
                result = await OnForgotPassword();
                //await Navigation.PushAsync(new LogoutPage(result));
            }
            else if (ex.ErrorCode != "authentication_canceled")
            {
                await DisplayAlert("An error has occurred", "Exception message: " + ex.Message, "Dismiss");
            }
        }
    }
Viewing all 91519 articles
Browse latest View live


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