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

GetUrlForUbiquityContainer Method Returns a Value In Xamarin.iOS but is NULL in Xamarin Forms - Why?

$
0
0

Hello, all:

This might sound like a Xamarin.iOS question at first, but it's actually about Xamarin Forms, so bear with me.

I am interested in adding iCloud functionality to a Xamarin Forms app I'm writing. I am new to iCloud, and have seen the Microsoft site's Xamarin documentation on incorporating iCloud to a Xamarin Forms app. But as a way of learning to trust the whole approach, I did the following first:

1) On a MacBook, with Xcode, I created a very basic native iOS Swift app that just calls iCloud and creates a simple text file, nothing else. This works just fine - I can see documents created in my iCloud account.

2) On the same MacBook, but using Visual Studio for Mac, I created the same very basic native iOS app that calls iCloud, but using C#. Again, this second effort works just fine - I can see text file documents created in my iCloud account.

I am now at a point where I'm wanting to replicate the iCloud functionality from the Xamarin.iOS project (in #2 above) into a regular Xamarin Forms project, where the code should fit into the Xamarin.iOS folder. I am now running on a Windows 10 machine with Visual Studio. I had hoped I could simply copy the code from the Xamarin.iOS standalone project (#2 above) into the full Xamarin project, the Xamarin.iOS folder.

No dice. For one thing, the standalone Xamarin.iOS project has a clearly defined view controller file of its own. The Xamarin.iOS folder inside the Xamarin Forms project doesn't have any such thing - the AppDelegate.cs file calls global::Xamarin.Forms.Forms.Init() followed by LoadApplication(new App()). If there's a ViewDidLoad in the mix, I can't find it.

Since Xamarin Forms abstracts the whole process of creating the UIViewController object under the covers, I can't find any reference to the ViewDidLoad event anywhere. This appears to be an issue because in the Xamarin.iOS standalone project, when the following code block executes in ViewDidLoad there:

           ThreadPool.QueueUserWorkItem(_ => {
                containerUrl = NSFileManager.DefaultManager.GetUrlForUbiquityContainer(null).Append("Documents", true);
                Console.WriteLine(">>> containerUrl = " + containerUrl);
            });

...the NSFileManager.DefaultManager.GetUrlForUbiquityContainer method returns a value as I expect. In the Xamarin Forms project, where I call the same code via a DependencyService call, as this:

            DependencyService.Get<ICloudHelper>().iCloudHelperInit();

...the result of the GetUrlForUbiquityContainer method is NULL. My method iCloudHelperInit uses that SAME ThreadPool code block above, but the result is nothing, and my app crashes due to a NullReferenceException.

When I stepped through the code in my Xamarin Forms version of this app, it appears the DefaultManager's folder referred to a path on my iPhone device rather than a path to iCloud.

So I suppose I have several questions here:

A.) Am I doing something wrong in Xamarin Forms that I'm not seeing a value returned from GetUrlForUbiquityContainer? Or is this a bug? Or is this a bug for Debug only? I saw a post elsewhere on another site saying that GetUrlForUbiquityContainer returns nulls running in debug mode. Again, I consistently see a non-null value returned and normal processing if it's strictly a Xamarin.iOS project, no other platforms.

B.) Is there a way to access/override the ViewDidLoad event or, for that matter, any of the other events in a UIViewController? Or is that a no-no with all the stuff that Xamarin Forms does under the covers to handle generating an iOS screen that looks native?

C.) What's the best way to get a non-null value from a call to GetUrlForUbiquityContainer?

D.) Should I consider using a .NET Standard Library to accomplish calls to iCloud from any of the three folders in my Xamarin Forms project - Xamarin.Android, Xamarin.iOS and Xamarin.UWP?

Thanks, folks!


Auto srolling listview /collectionview with controlling the scroll speed from top to buttom.

$
0
0
Auto srolling listview /collectionview with controlling the scroll speed from top to buttom. I can achieve the scrollto.end but can't control the speed. I want scrolling it very slowly.

Proper way to implement OnAppLinkRequestReceived in Xamarin Shell

$
0
0

Hi,

I am trying to get the my app to open a specific page in response to a link. In my MainActivity.cs I have the following intent filter, which seems to be working fine:

    [IntentFilter(new[] { Intent.ActionView },
        Categories = new[]
        {
            Intent.ActionView,
            Intent.CategoryDefault,
            Intent.CategoryBrowsable
        },
        DataScheme = "http",
        DataHost = "api.myapp.com",
        DataPathPrefix = "/posts/")]

In my App.xaml.cs I have

    protected async override void OnAppLinkRequestReceived(Uri uri)
        {
            string appDomain = "http://api.myapp.com/";
            // Removed extra code for brevity
            if(page == "posts")
            {
                if(MainPage == null)
                {
                    MainPage = new Shell();
                }

                int postId;
                if (int.TryParse(pageParameter, out postId))
                {
                    await Shell.Current.GoToAsync($"//Main/MyApp?postId={postId}");
                }
            }

            base.OnAppLinkRequestReceived(uri);
        }

I was wondering if it is normal that the MainPage is null (i.e. it is creating a new instance of the app instead of using an existing one) when it receives the link uri? If so, is it good to set the MainPage to a new Shell? What is the best practice?

Also, as a side question, why does typing in http://api.myapp.com/posts/7 work in my Android phone's google search app but not in chrome web browser? In chrome it just opens the website without giving me an option to open it in the app.

Thanks for reading this.

Animate label without resetting timeout duration

$
0
0

I have following method to animate a label for 20 seconds.

private async void Animate(object obj, PropertyChangedEventArgs e)
        {

            if (e.PropertyName == "ClassId")
            {
                VisualElement sender = obj as VisualElement;
                var parentAnimation = new Animation();
                var fadeOutAnimation = new Animation(d => sender.Opacity = d, 1, 0, Easing.Linear);
                var fadeInAnimation = new Animation(d => sender.Opacity = d, 0, 1, Easing.Linear);
                parentAnimation.Add(0, 0.5, fadeOutAnimation);
                parentAnimation.Add(0.5, 1, fadeInAnimation);
                parentAnimation.Add(0, 0.5, fadeOutAnimation);
                parentAnimation.Add(0.5, 1, fadeInAnimation);
                parentAnimation.Add(0, 0.5, fadeOutAnimation);
                parentAnimation.Add(0.5, 1, fadeInAnimation);
                parentAnimation.Add(0, 0.5, fadeOutAnimation);
                parentAnimation.Add(0.5, 1, fadeInAnimation);
                parentAnimation.Commit(sender, "BlinkingVisualElement", 16 , 800, repeat: () => true);
                await Task.Delay(20000);
                parentAnimation.Commit(sender, "BlinkingVisualElement", 16, 800, repeat: () => false);
            }
        }

This method can get called multiple times within 20 seconds. It works fine and animates the label for full 20 seconds,if called one time and wait for 20 seconds before firing second call. I want it to animate 20 seconds whenever this method is fired.

Now what is happening

I called the method first time on

9:00:00 AM

It animates till 9:00:20

If i call the method second time on

9:00:12 AM

It still animates till 9:00:20 only(8 seconds only). I want it to animate till 9:00:32

Basically i want to reset the timer and show full 20 seconds animation whenever the event is fired

Xamarin.Android Crash on BluetoothLeScanner.StartScan

$
0
0

During testing Bluetooth application, I have cautch the following exception System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.' on call:

BluetoothLeScanner.StartScan

... It is very strange, and I even do not know where it is thrown ...

Have anyone faced with the same issue ?

Media Element crash when navigating away from page on Ios

$
0
0

I am getting Media Element disposing exception when I navigate back to a previous page from a page where I have my Media Element.

The managed Managed Stacktrace:

          at <unknown> <0xffffffff>
          at ObjCRuntime.Messaging:void_objc_msgSend_IntPtr <0x00007>
          at AVFoundation.AVPlayer:ReplaceCurrentItemWithPlayerItem <0x0005b>
          at Xamarin.Forms.Platform.iOS.MediaElementRenderer:Dispose <0x002b7>
          at Foundation.NSObject:Dispose <0x00023>

My steps to reproduce were:
Push new page with MediaElement. Click play on video.
Click back to pop page.
Page does pop but UI becomes unresponsive.

my code is:

public partial class SermonsMediaPlayer : ContentPage
            {
                private Sermon Sermon;

                public SermonsMediaPlayer(Sermon selectedSermon)
                {
                    InitializeComponent();

                    if (selectedSermon is null)
                    {
                        Sermon = new Sermon();
                    }

                    Sermon = selectedSermon;
                    BindingContext = Sermon;

                }

                async void Back_Clicked(object sender, EventArgs args)
                {
                    // release media resources
                    if (mediaPlayer.CurrentState == MediaElementState.Playing)
                    {

                        mediaPlayer.Stop();
                        await Navigation.PopModalAsync();
                    }

                    await Navigation.PopModalAsync();
                }

                protected override void OnDisappearing()
                {
                    base.OnDisappearing();
                }
            }


        <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="xxxViews.SermonsMediaPlayer">
            <ContentPage.ToolbarItems>
                <ToolbarItem Text="Back" Clicked="Back_Clicked" />
            </ContentPage.ToolbarItems>
            <ContentPage.Content>
                <Grid>
                    <MediaElement x:Name="mediaPlayer" Source="{Binding Url}" AutoPlay="False"
                      ShowsPlaybackControls="True" KeepScreenOn="False" />
                </Grid>
            </ContentPage.Content>
        </ContentPage>

Xamarin.Forms How to create custom Forms view

$
0
0

I have faced with issue that I do not know how to create custom Forms view that renders differently on each platform Android, iOS ...
On Android it is FrameLayout with some custom content, on iOS it is another view or layout with custom content ...

Seems like I have to use Custom Renderer, but I do not know which Renderer to use ... ViewRenderer, FrameRenderer, MapRenderer ...

I mean I do not have class from which I can inherit from like in this example:

    public class MyEntry : Entry
    {
    }

    public class MyEntryRenderer : EntryRenderer
    {
        protected override void OnElementChanged (ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged (e);

            if (Control != null) {
                // do whatever you want to the UITextField here!
                Control.BackgroundColor = UIColor.FromRGB (204, 153, 255);
                Control.BorderStyle = UITextBorderStyle.Line;
            }
        }
    }

I do not have class like Entry because on each platform I have specific rendering ...

Can somebody show direction ?

ListView : Items are duplicated

$
0
0

Hello everyone !
Here is my issue, on my ListView I have an button inside, when i'm clicking on it, the color change, but when i'm scrolling further in my list, some others buttons (every 5 or 7 rows) with the new color whereas I didn't do anything.

I'm using in my ListView the RecycleStrategy because I have more than 100 items.

Do you know how can I handle that ? Thanks !


CollectionView disable selection of an item in collection

$
0
0

I'm working with the CollectionView (with a selection mode of Multiple) and I'm having problems disabling the selection of an item in the collection. As a result, I'm attempting to reverse the selection of the item instead of disabling selection of that item.

I've looked at determining the value of an item passed in the OnSelectionChanged event, and then trying to reverse the action selection (or deselection) of the item, but I'm running into looping issues with the OnSelectionChanged event getting triggered on the reversal of the item. Anyone know a good way to handle this?

How to cancel a page loading during OnAppearing

$
0
0

Firstly, let me say I am new to Xamarin and Android and am trying to migrate some apps from Windows CE. It's a steep learning curve.

I and trying to stick to MVVM principles but think I am missing some basic understanding of the page lifecycle.
I want to show a page. Before showing it, I need to check and open some text files and if this fails for any reason, display a message and stop the page from showing.
Ideally it would immediately tidy some stuff up and close it.

I am using navigation so call this from a button click on my main page:
await Navigation.PushAsync(new MyPage());

I am checking the files in the OnAppearing event in MyPage.xaml.cs.
private void MyPage_OnAppearing(object sender, System.EventArgs e)
{
if (!myPageViewModel.CheckFiles())
Application.Current.MainPage.Navigation.PopAsync(); //Close this page (Pop the page off the top of the navigation stack)
}

If it fails, the page is still visible.
This is just one method I have tried, it doesn't do what I need and suspect that this is not the right way to do it anyway.

In WinCE I would check the files in the Form Load or Shown event and call Close before the form becomes visible.

Any suggestions would be very welcome.

Is it possible to replace a colour inside an Image object?

$
0
0

Hi All,

I am currently working on a speech generation device for children using Xamarin.Forms, and I was trying to create the ability for the pictograms that depict people to have the skin tone change dynamically based upon which one is set in the application's settings. I have created non-aliased drawable resources that contain sections that are set to chromakey green, like such:

Ideally, I would like to be able to read said image, replace any chromakey green pixels with the relevant skin tone colour, then return that object to the caller. I have seen some references online to converting the image to a bitmap, then going through each pixel to replace with the correct colour, but I am struggling to find anything that might work cross platform on Android, iOS and UWP.

Has anyone done anything like this? I could create a new image pictogram for each skin tone, but that will blow out the number of pictograms by about 8 times, which will make it difficult for the user to browse (the end application is going to have some four or five hundred pictograms)

Regards
Ryan Abrahams

How do I publish a message from a static class?

$
0
0

I have code that follows the pattern below. (Sorry for its length; this is a problem spread across a few files.)

I have a base class that implements a system like INotifyPropertyChanged but uses the Xamarin.Forms.MessagingCenter.

The first property IsBusy works fine. The class consuming the messages, SomeClassTryingToReceiveMessages, gets the message.

My problem comes in AnotherProperty, which is static and therefore does not have a this reference to use as the source of the type information in the message. I have tried all sorts of expressions in the setter but can't find one that is picked up by the consuming class.

Does anyone know how to do this or even if it is possible?

public abstract class ModelBase
{
    protected void NotifyModelStateChanged<S>( S subclass, string propertyName ) where S : ModelBase
    {
        Messaging.Publish( subclass, "StateChanged", propertyName );
    }

    protected bool SetProperty<S,T>( S subclass, ref T oldValue, T newValue, [CallerMemberName] string propertyName = null ) where S : ModelBase
    {
        if( !oldValue.Equals( (T)newValue ) )
        {
            oldValue = newValue;
            NotifyModelStateChanged( subclass, propertyName );
            return true;
        }
        return false;
    }
}


public abstract class SessionBase : ModelBase
{
    public bool IsBusy
    {
        get => _isBusy;
        set => SetProperty( this, ref _isBusy, value );
    }

    public static bool AnotherProperty
    {
        get => _anotherProperty;
        private set
        {
            Hub.Messaging.Publish( /* WHAT DO I WRITE HERE? */, "StateChanged", nameof(AnotherProperty) );
        }
    }

    private bool _isBusy = false;
    private static bool _anotherProperty = false;
}

public class ConcreteClass : SessionBase
{
    // This is the class that gets instantiated and is actually the publisher of the messages.
}


public void SomeClassTryingToReceiveMessages()
{
    public SomeClassTryingToReceiveMessages()
    {
        Hub.Messaging.Subscribe<SessionBase,string>( this, "StateChanged", HandleStateChangedMessage );
    }

    private void HandleStateChangedMessage( SessionBase session, string propertyName )
    {
        // Act on received message.
    }
}


How to implement Horizontal ListView inside Vertical ListVIew ?

$
0
0

Hi All, I need to create a screen having horizontal list inside vertical listview in xamarin forms

I am able to display the items properly but I need a click event on horizontal list (inner list) item.

Can anyone help ? or any other approach to create below design?

Is there a way to do automation testing in Xamarin.Forms WPF app?

$
0
0

Hi, I am developing an app using Xamarin Forms which supports all there platforms. For Windows, I am using Xamarin.Forms.WPF library to develop my desktop application. I wanted to implement automation testing in my app for which I gave automation ID to all UI components. I am able to write automation scripts for both iOS and Droid but I am unable to do in Windows. I tried using the WinAppDriver automation tool but I am unable to fetch the automation ID in my scripts. I also analyzed the Xamarin.Forms.WPF library in which there is no implementation for automation. Is there any way to do automation for my Windows app?

Facing issue with VS 8.7.2 (build 4)

$
0
0

I am using VS for developing mac application, i recently updated VS to 8.7.2, after that whenever i opened Xcode and did some changes, all the custom class that i created and mapped in that storyboard will regenerated in VS while sync. Eg: I have a storyboard named Aa.storyboard inside resources/Base.proj and a custom class for NSbutton called NiceButton.cs, that i used inside Aa storyboard for beautification of a button. Whenever i opened Aa storyboard and did a small changes and after sync with Xcode, VS automatically creates a folder named Base.proj inside root folder and add the NiceButton.cs in it. I upgraded Xcode to 11.6 and OSX to 10.15.6, but still issue exists.

Is there any way to downgrade VS, i am blocked because of this. Please help me


How to set frame border width in xamarin forms

$
0
0

In my application i need to set the border width for frame. There is no property like that. How to achieve the border width for frame in xamarin froms

MasterDetailPage icon right and drawer open from right to left

$
0
0

Hi
How MasterDetailPage icon align to right?
and how drawer open from right to left?
Please give us code if you did it. Thank you

ItemsUpdatingScrollMode in CollectionView

$
0
0

Hello,

ItemsUpdatingScrollMode="KeepLastItemInView"

It works fine the first time I enter the page, the list scrolls in the last item, but then I go back in, the item is in the first, I have to open and close the application again and everything works the first time

Xamarin Forms iOS Label does not display correctly in ListView

$
0
0

Hello,

I have an iOS ListView that has a Datagrid with a Group Header Template. The issue I am having is when a label within the Gridview attempts to display in iOS, the label is displaying partially.

ie.

When it First Loads

If you were to click on the Dates in DataView..you can see the label overlaying dates...

XAML code

<ListView x:Name ="lstView"
IsGroupingEnabled="true"

                       SeparatorVisibility="None"
                  HorizontalOptions="FillAndExpand"
                  VerticalOptions="FillAndExpand" 
                HasUnevenRows="true">
                    <ListView.GroupHeaderTemplate>
                        <DataTemplate>
                            <ViewCell >

                            <Grid RowSpacing="0" BackgroundColor="#00AEEF">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="*" />
                                    <RowDefinition Height="*"/>                                    

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

                                </Grid.ColumnDefinitions>


                                <StackLayout Grid.Row="0"  HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" >


                                    <Label Grid.Row="0" Text="{Binding LongName}" Padding="10" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" FontAttributes="Bold" TextColor="White" FontSize="Large" ></Label>

                                </StackLayout>


                                <StackLayout Grid.Row="1" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">



                                    <Label x:Name="HeaderDesc" Text="{Binding HeaderDescription}" Padding="10,20" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" TextColor="White" FontSize="Medium" FontAttributes="Italic"></Label>



                                </StackLayout>



                               </Grid>




                            </ViewCell>

                        </DataTemplate>
                    </ListView.GroupHeaderTemplate>
                    <ListView.ItemTemplate>
                        <DataTemplate>

                        <!--TextCell Text="{Binding startDate}"
                                   TextColor="#00AEEF"

                                 >


                        </TextCell-->
                        <ViewCell Height="45">

                            <StackLayout   HorizontalOptions="FillAndExpand"                                            
                                       Spacing="10" 
                                        Padding="7,0,0,10"
                                       Opacity="0.9"
                                       >

                                <Label
                                        Text="{Binding startDate}"  
                                   FontSize="Subtitle"
                                   TextColor="#00AEEF" 
                                   FontAttributes="None" 
                                   VerticalOptions="Center" 
                                   HorizontalOptions="FillAndExpand" />
                            </StackLayout>

                        </ViewCell>

                    </DataTemplate>






                </ListView.ItemTemplate>



            </ListView>

As you can see the second label, (HeaderDesc) is not appearing properly..you have to click on the DataTemplate field to see it. Options I have tried include, removing the stack layout, and setting the height to 20 or auto; but still same issue persists. I just cannot get Row 1 contents to display correctly.

Your direction would be very much appreciated.

Thank you!

how to reveal whether an event was caused by a user

$
0
0

I have a picker , and an event handler

 private async void TopicsPicker_OnSelectedIndexChanged(object sender, EventArgs e)
{
    ....
}

This event handler is being called in these 2 cases:
1. By user: The user selects a new option in the picker.
2. By code: myPicker.SelectedIndex =....

In these 2 cases I would like to perform 2 different actions.

How can I reveal in the event handler who called it- the user or the code.

P.S I tried
var answer = new StackFrame(1).GetMethod().Name;
It just gave me the result "Start()" no matter if it was caused by user or by code.
In [CallerMemberName] I can't user, because this is an event hander, and it will brake the signature.

Viewing all 79144 articles
Browse latest View live


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