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

Is there a placeholder for Xamarin Forms 3.6 Datepicker with material visual?

$
0
0

I'm using the Xamarin Forms 3.6 material visual. I have a contentpage with both Entry and DatePicker controls. Entry renders a placeholder great - however, a datepicker does not appear to have an option for a placeholder/title/label.

Looking to see if anyone else has come across this? Will this be a custom renderer?


Error with AdMob custom renderer..

$
0
0

I am trying below code but having errors..

'AdMobRenderer.OnElementChanged(ElementChangedEventArgs)': no suitable method found to override

'View' is an ambiguous reference between 'Xamarin.Forms.View' and 'Android.Views.View'

'AdMobRenderer.OnElementPropertyChanged(object, PropertyChangedEventArgs)': no suitable method found to override

The type or namespace name 'PropertyChangedEventArgs' could not be found (are you missing a using directive or an assembly reference?)

Argument 1: cannot convert from 'Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Xamarin.Forms.View>' to 'Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Samana.AdMobView>'

Kindly helpp....

here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Gms.Ads;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Samana.Droid;
using Samana;

[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobRenderer))]
namespace Samana.Droid
{
    public class AdMobRenderer : ViewRenderer<AdMobView, AdView>
    {
        Context context;

        public AdMobRenderer(Context _context) : base(_context)
        {
            context = _context;
        }

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

            if (e.NewElement != null && Control == null)
                SetNativeControl(CreateAdView());
        }

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

            if (e.PropertyName == nameof(AdView.AdUnitId))
                Control.AdUnitId = Element.AdUnitId;
        }

        private AdView CreateAdView()
        {
            var adView = new AdView(Context)
            {
                AdSize = AdSize.SmartBanner,
                AdUnitId = Element.AdUnitId
            };

            adView.LayoutParameters = new LinearLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);

            adView.LoadAd(new AdRequest.Builder().Build());

            return adView;
        }
    }
}

Kindly help....

Thanks,
Jassim

Simple example for creating a Bottom Toolbar in Xamarin Forms.

$
0
0

Can you create a Bottom Toolbar in Xamarin Forms? There isn't a useful example on the internet. Most of the examples are for Native Android. Does someone have a little example?

Thanks!

Xamarin.Essentials: File System Helpers

$
0
0

Hello,
I try to use File System Helpers for my project. But for Android the stream returned by FileSystem.OpenAppPackageFileAsync doesn't support random access. CanSeek is false, Length and Position are not supported. This complicates things a lot. The only way to get a file size for example is to read per byte and count them. This itself may not be a big issue but reading is extremely slow too. Many times slower than for UWP. For UWP it works fully. I mean random access is supported and reading is fast as it's supposed to be.
Why is this? It kind of defeats the purpose of File System Helpers since it's nearly unusable for Android.

Shell - Content page renders under tabs and title

$
0
0

When using shell and tabs, the content page is rendering under the tabs and header.

<?xml version="1.0" encoding="UTF-8"?>
<Shell 
    xmlns:local="clr-namespace:WeAreVoice.Mobile" 
    RouteScheme="app" 
    RouteHost="microsoft.com"
    Route="newapp" 
    FlyoutBehavior="Disabled"
    x:Class="WeAreVoice.Mobile.AppShell">

    <ShellItem>

        <ShellSection Title="Feed">
          <ShellContent>
            <local:FeedPage />
          </ShellContent>
        </ShellSection>

        <ShellSection Title="Groups">
             <ShellContent>
                <local:GroupPage />
             </ShellContent>
        </ShellSection>

  </ShellItem>

</Shell>

Group Page

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage 
x:Class="WeAreVoice.Mobile.GroupPage"
             Title="Groups">
    <ContentPage.Content>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="110" />
                <RowDefinition Height="*" />
                <RowDefinition Height="110" />
            </Grid.RowDefinitions>
            <BoxView
                BackgroundColor="Red"
                Grid.Row="0"
                Grid.Column="0" />
            <BoxView
                BackgroundColor="Blue"
                Grid.Row="1"
                Grid.Column="0" />
            <BoxView
                BackgroundColor="Green"
                Grid.Row="2"
                Grid.Column="0" />
        </Grid>
    </ContentPage.Content>
</ContentPage>

When not using shell but classic tabbed page it is rendered as expected

Tabbed Page

<?xml version="1.0" encoding="utf-8"?>
<TabbedPage 
    xmlns:local="clr-namespace:WeAreVoice.Mobile" 
    x:Class="WeAreVoice.Mobile.MainPage"
    xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
    android:TabbedPage.ToolbarPlacement="Bottom">
    <NavigationPage Title="Feed">
        <x:Arguments>
            <local:FeedPage />
        </x:Arguments>
    </NavigationPage>
    <NavigationPage Title="Groups">
        <x:Arguments>
            <local:GroupPage Title="Groups" />
        </x:Arguments>
    </NavigationPage>
</TabbedPage>

Is this a bug in the shell?

To bad I cannot include screenshots because of the forum policy.

Prism with Picker in Listview

$
0
0

Hi,

I'm having real trouble with the Picker binding in a Listview that it would be great to get some assistance with. I'll be retrieving ListView Items via an API and also adding Items to the ListView (and then saving via API).

Basically I have an List() as Picker ItemsSource as follows:

public class RFIOptionDto
{
    public int RFIOptionId { get; set; }
    public string Value { get; set; }
}

and so far I've ended up with the following as my ListView items:

public class TextCategoryDto : BindableBase
{
        public IEnumerable<RFIOptionDto> RFIOptions { get; set; }    
        public int TextCategoryId { get; set; }    
        public int? RFIOptionId { get; set; }

        private RFIOptionDto _selectedRFIOption;           
        public RFIOptionDto SelectedRFIOption
        {
            get { return _selectedRFIOption; }
            set { SetProperty(ref _selectedRFIOption, (RFIOptions != null && RFIOptionId != null) ? RFIOptions.SingleOrDefault(c => c.RFIOptionId == RFIOptionId) : value); }
        }

        private string response;
        public string Response
        {
            get { return response; }
            set { SetProperty(ref response, value); }
        }
}

Here's my ViewModel:

private DelegateCommand<TextCategoryDto> _entryUnfocusedCommand;
public DelegateCommand<TextCategoryDto> EntryUnfocusedCommand => _entryUnfocusedCommand ?? (_entryUnfocusedCommand = new DelegateCommand<TextCategoryDto>(EntryUnfocused));

private DelegateCommand<TextCategoryDto> _pickerUnfocusedCommand;
public DelegateCommand<TextCategoryDto> PickerUnfocusedCommand => _pickerUnfocusedCommand ?? (_pickerUnfocusedCommand = new DelegateCommand<TextCategoryDto>(PickerUnfocused));

public IEnumerable<RFIOptionDto> RFIOptions { get; set; }

private ObservableCollection<TextCategoryDto> textCategories;
public ObservableCollection<TextCategoryDto> TextCategories
{
    get { return textCategories; }
    set { SetProperty(ref textCategories, value); }
}

public async override void OnNavigatingTo(INavigationParameters parameters)
{
    RFIOptions = parameters.GetValue<IEnumerable<RFIOptionDto>>("RFIOptions");

        try
        {
            var apiResponse = RestService.For<IRFIRepository>(Settings.BaseURL, new RefitSettings()
            {
                AuthorizationHeaderValueGetter = () => Task.FromResult(Settings.AccessToken)
            });

            var rfiDto = await apiResponse.GetTextCategoriesForRFI(RFIId);

            TextCategories = new ObservableCollection<TextCategoryDto>(rfiDto.TextCategories);

            base.OnNavigatingTo(parameters);
        }
        catch (Exception ex)
        {

        }
}

private async void PickerUnfocused(TextCategoryDto textCategoryDto)
{
    //Save TextCategory via API
}

private async void EntryUnfocused(TextCategoryDto textCategoryDto)
{
    //Save TextCategory via API
}

And the ListView;

    <ListView x:Name="textCategoriesListView" ItemsSource="{Binding TextCategories}" 
                      HasUnevenRows="True" 
                      VerticalOptions="FillAndExpand" 
                      Margin="0,0,0,0"
                      SelectionMode="None"
                      CachingStrategy="RecycleElement"
                      Grid.Column="0"
                      Grid.Row="0">

                    <ListView.ItemTemplate>
                        <DataTemplate>

                            <ViewCell x:Name="textCategoryViewCell">

                                <ViewCell.View>

                                        <StackLayout Margin="10,20,10,20">

                                            <Picker Title="Select Category" TitleColor="#999999"
                                                HorizontalOptions="FillAndExpand"
                                                TextColor="#FFFFFF"
                                                BackgroundColor="#4c5a63"
                                                FontSize="14"
                                                ItemsSource="{Binding RFIOptions}"
                                                ItemDisplayBinding="{Binding Value}"
                                                SelectedItem="{Binding SelectedRFIOption}">

                                                <Picker.Behaviors>
                                                    <behaviors:EventHandlerBehavior EventName="Unfocused">
                                                        <behaviors:InvokeCommandAction Command="{Binding BindingContext.PickerUnfocusedCommand, Source={x:Reference Name=textCategoriesListView}}"
                                                                                        CommandParameter="{Binding .}"/>
                                                    </behaviors:EventHandlerBehavior>
                                                </Picker.Behaviors>

                                            </Picker>

                                            <Label Text="Enter Value" 
                                               TextColor="#ea5c2d" 
                                               HorizontalOptions="Start" />

                                            <Entry Placeholder="Enter Value" 
                                               PlaceholderColor="#999999" 
                                               FontSize="14"
                                               Text="{Binding Response}" 
                                               TextColor="#FFFFFF" 
                                               BackgroundColor="#4c5a63">

                                                <Entry.Behaviors>
                                                    <b:EventToCommandBehavior EventName="Unfocused" 
                                                                                Command="{Binding BindingContext.EntryUnfocusedCommand, Source={x:Reference Name=textCategoriesListView}}"
                                                                                CommandParameter="{Binding .}"/>
                                                </Entry.Behaviors>

                                            </Entry>

                                        </StackLayout>

                                </ViewCell.View>

                            </ViewCell>

                        </DataTemplate>
                    </ListView.ItemTemplate>

                </ListView>

On the PickerUnfocused Command the the SelectedRFIOption doesn't show the changed Picker TextCategoryDto item:

textCategoryDto.RFIOptionId = textCategoryDto.SelectedRFIOption.RFIOptionId;

And it can't be right that I'm having to do the following on the setter of the SelectedRFIOption property in the TextCategoryDto:

private RFIOptionDto _selectedRFIOption;           
public RFIOptionDto SelectedRFIOption
{
    get { return _selectedRFIOption; }
    set { SetProperty(ref _selectedRFIOption, (RFIOptions != null && RFIOptionId != null) ? RFIOptions.SingleOrDefault(c => c.RFIOptionId == RFIOptionId) : value); }
}

However if the SelectedRFIOption property is as follows:

public RFIOptionDto SelectedRFIOption
{
    get { return _selectedRFIOption; }
    set { SetProperty(ref _selectedRFIOption, value); }
}

The SelectedItem is not visible in the Picker for existing TextCategories from the API despite being set in the retrieved data. I saw this post by @DarkSummon which looks like it explains why:

https://forums.xamarin.com/discussion/100717/picker-custom-control-property-pass-through-itemdisplaybinding

But adding the override ToString() property made no difference.

Can anyone see anything obvious I'm missing? Any help much appreciated.

Youtube embedded in webview playback stops after second on ios device, but it plays on simulator

$
0
0

Hi,

I want to play a embedded youtube video in an Xamarin forms application. I have an article feed in which I sometimes want to display a youtube video.

My solutions works great on android and displays an inline youtube video in the given webview nicely. On iOS it switches to fullscreen. That is not preferred but not a problem. However on a device the playback stops after a second, on the simulator it plays without a hitch. Is there something I am missing?

My code:

 HtmlWebViewSource source = new HtmlWebViewSource();
                source.SetBinding(HtmlWebViewSource.HtmlProperty, "HTMLDesc");
                source.Html = $@"<html>
        <body>  
        <iframe style="" position: absolute; top: 0; left: 0; width: 100%; height: 100%;""  src=""{ Article.Youtube }"" frameborder=""0"" allowfullscreen>
        </iframe></body></html>";
                var webView= new WebView();
                webView.Source = source;
                someContentview.Content= WebView;

Kind regards,

Adding a placeholder and aligning text to center on DatePicker

$
0
0

I'm having trouble with adding a placeholder to my DatePicker (doesn't have title property like a regular picker). I have a custom renderer:

public class DOBPicker : DatePicker { public static readonly BindableProperty EnterTextProperty = BindableProperty.Create(propertyName: "Placeholder", returnType: typeof(string), declaringType: typeof(DOBPicker), defaultValue: default(string)); public string Placeholder { get; set; } }

iOS Renderer:

`protected override void OnElementChanged(ElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (this.Control == null)
return;
var element = e.NewElement as DOBPicker;
if (!string.IsNullOrWhiteSpace(element.Placeholder))
{
Control.Text = element.Placeholder;
}

       Control.ShouldEndEditing += (textField) => {
           var seletedDate = (UITextField)textField;
           var text = seletedDate.Text;
           if (text == element.Placeholder)
           {
               Control.Text = DateTime.Now.ToString("dd/MMMM/yyyy");
           }
           return true;
       };
    }
    private void OnCanceled(object sender, EventArgs e)
    {
        Control.ResignFirstResponder();
    }
    private void OnDone(object sender, EventArgs e)
    {
        Control.ResignFirstResponder();
    }`

It works, but when I go back to the previous page, the app crashes and I get an error (Object reference not set to an instance of an object). I think it's referring to

if (!string.IsNullOrWhiteSpace(element.Placeholder)) { Control.Text = element.Placeholder; }


When can we use .Net Standard 2.0 for Xaamarin.Forms on VS Mac?

$
0
0

Now we can create Xamarin.Forms project based on .Net Standard 2.0 on VS 2017, but we cannot do that on Mac, nor can we open an .Net Standard Xamarin project created by VS 2017.

Any plan for Thant?

How to implement below wavesurfar design?Please advice

How to detect PopAsync back to MainView

$
0
0

There is my code:

    public partial class App : Application
    {
        public App()
        {
            MainPage = new NavigationPage(new MainPage());
        }
    }

    public partial class MainPage : ContentPage
    {
        private void Button_Clicked(object sender, EventArgs e)
        {
            this.Navigation.PushAsync(new ChannelPage());
        }
    }

public partial class ChannelPage : ContentPage
{
    private async void Channel_Clicked(object sender, EventArgs e)
    {
        await Navigation.PopAsync();
    }
}

When await Navigation.PopAsync(); run, the current page will back to MainPage.
The ChannelPage will modify some values,
so I need do some process when back to MainPage finish.

I want to know which override function can handle this event in MainPage?

Carousel with dots to show how many screens

$
0
0

The carousel sample does not have dots to indicate how many screens of swiping there is.

Is this a property to set or is there a way to easily do that?

Xamarin.Forms android app exit alert

$
0
0

I want when user press 'back button' on android device to exit my app, there is a alert dialog shown to ask user 'Do you want to exit ? (Yes, No)'.

https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.application.pagedisappearing?view=xamarin-forms
I found 'Application.PageDisappearing Event', but I don't know how to write the code.
I have never write the code to work with Event variable.

I need to do the exit alert because my app have TcpClient connection, if the app exit the connection will be disconnect.
I want user use 'home button' to let my app go background, that will be keep the connection alive.

"Today" button for DatePicker?

$
0
0

Hello all!

In our desktop product, our calendar control has a "today" button. It would be handy to have that feature available on the mobile product. Does anyone have any hints as to how that might be accomplished?

I know the obvious answer is to put a button next to the date picker anchor in the main UI, but (stop me if you've heard this one...) I don't really have space. I was kind of hoping to find a way to get it to show up in the picker dialog that pops up. Any suggestions?

Thanks!
-Karen

SocketAsyncResult.CheckIfThrowDelayedException () exception on Android

$
0
0

I have below exception when i want to connect to my api. This exception is happening in some special cases. for example, when I am in my gym, i am able to reproduce it. my gym is having a wireless connection using this service https://www.freefii.de/
when I connect to it, general internet connection is fine and fast but somehow my app is returning this exception every time i make api request.
Any idea what could be the problem?

"type": "System.Net.WebException",
"message": "Error: ConnectFailure (Network subsystem is down)",
"stackTrace": " at System.Net.WebConnection.Connect (System.Net.WebOperation operation, System.Threading.CancellationToken cancellationToken) [0x00217] in :0 \n at System.Net.WebConnection.InitConnection (System.Net.WebOperation operation, System.Threading.CancellationToken cancellationToken) [0x000cc] in :0 \n at System.Net.WebOperation.Run () [0x0009a] in :0 \n at System.Net.WebCompletionSource1[T].WaitForCompletion () [0x00094] in <a13a876c512b4bd799407c195d4b8176>:0 \n at System.Net.HttpWebRequest.RunWithTimeoutWorker[T] (System.Threading.Tasks.Task1[TResult] workerTask, System.Int32 timeout, System.Action abort, System.Func`1[TResult] aborted, System.Threading.CancellationTokenSource cts) [0x000f8] in :0 \n at System.Net.Http.HttpClientHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x002e7] in :0 ",

here is the code I am using;

 private static HttpClient getClient()
        {
                  HttpClientHandler handler = new HttpClientHandler
                    {
                        Proxy = Xamarin.Forms.DependencyService.Get<Helpers.IProxyInfoProvider>().GetProxySettings()
                    };
                     HttpClient _client= new HttpClient(handler);

                  return _client;
     }

 using (HttpClient client = getClient())
       {
                 HttpResponseMessage response = await client.GetAsync(uri, ct)
        }

In Android Project

 public class ProxyInfoProvider : IProxyInfoProvider
    {
        public WebProxy GetProxySettings()
        {
            string proxyHost = JavaSystem.GetProperty("http.proxyHost");
            string proxyPort = JavaSystem.GetProperty("http.proxyPort");

            return !string.IsNullOrEmpty(proxyHost) && !string.IsNullOrEmpty(proxyPort)
                ? new WebProxy($"{proxyHost}:{proxyPort}")
                : null;
        }
    }

Version bumping for for DevOps builds

$
0
0

I used to use a script to
1. Check out appmanifest.xml / info.plist
2. Add +1 to the versioncode
3. Check the file back in again

Now we moved to Azure devops and I'm redoing some of the build-strategies. One thing I came across was James Montemagnos Mobile App Tasks.

From what I can tell, this tasks does not use the old version+1. Instead it uses $Build.BuildId from Azure DevOps (at least as it's example). Nor does it check out/in anything.

Just want to check with the rest of you. What strategy do you use? Checking in the new VersionCode or not?

How to play an youtube video through using youtube url in xamarin forms

$
0
0

Hi everyone, i want play an video through using youtube url. Here if i use webview its playing in youtube but again its not coming to My App.Is there any other way to do this.
can someone help me in this plz. source code will be more helpful. thanks in advance

How create round skbitmap

$
0
0

Hi, I need create round bitmap from SKBitmap

I get bitmap
public async Task GetPhoto()
{
try
{
Uri uri = new Uri();
WebRequest request =WebRequest.Create(uri);
WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
return SKBitmap.Decode(responseStream);
}
catch (Exception ex)
{

        }
        return new SKBitmap();
    }

Can I change back button icon to something else?

$
0
0

Hey guys, so like the title says, is it possible to change the Navigation bar back button icon to something else. I wanted to change the back button in certain pages, replacing it with a home image icon. Tried several methods, none of which worked. I want to do this in Android and IOS

Thanks in advance!

How to design a Animated SplashScreen?

$
0
0

I am trying to design a animated splash screen like this image..Any suggestion ?

Viewing all 91519 articles
Browse latest View live


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