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

Bound property not yet set when xaml tag requires it

$
0
0

Hi there, I'm trying to use code from the video example found here. However that example directly specifies the video source in the xaml, and I'm trying to bind that value. Unfortunately it seems by the time the property on the video control is set from the xml, the binding is not yet available. It seems there is something I'm missing about setup and binding order. Can anyone help me understand what I'm doing wrong here? More detail follows:

This uses a simple View, with a custom control (with an exported renderer), with it's "Source" set to a bound value:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:videoplayer="clr-namespace:BunAndBuneeTV.Controls.VideoPlayer"
             x:Class="BunAndBuneeTV.Views.VideoPlayerView">
    <videoplayer:VideoPlayer Source="{Binding EpisodePath}" AutoPlay="true"/>
</ContentPage>

The binding is to an equally simple viewmodel:

public class VideoPlayerViewModel :
    ViewModelBase
{
    private Episode episode;

    public string EpisodePath => (episode != null) ? episode.Path : string.Empty;

    #region ViewModelBase overrides
    public override async Task InitializeAsync(object navigationData)
    {
        episode = navigationData as Episode;

        await base.InitializeAsync(navigationData);
    }
    #endregion
}

The custom control includes the expected Source property (with a converter):

public class VideoPlayer : View, IVideoPlayerController
{
    // Lots of excluded detail..

    // Source property
    public static readonly BindableProperty SourceProperty =
        BindableProperty.Create(nameof(Source), typeof(VideoSource), typeof(VideoPlayer), null);

    [TypeConverter(typeof(VideoSourceConverter))]
    public VideoSource Source
    {
        set { SetValue(SourceProperty, value); } // This appears to only be called once, before the BindingContext is set
        get { return (VideoSource)GetValue(SourceProperty); }
    }
}

And finally the renderer uses Source in OnElementPropertyChanged:

public class VideoPlayerRenderer : ViewRenderer<VideoPlayer, UIView>
{
    // Lots of excluded detail..

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

    if (args.PropertyName == BnBVideoPlayer.SourceProperty.PropertyName)
        {
    var source = Element.Source;
    // Problem! source is null!
        }       
    }
}

I use a typical NavigationService pattern, so I'll save you the details of that, but fundamentally the order of execution here is:

var page = Activator.CreateInstance(pageType) as Page;
ViewModelBase viewModel = container.Resolve(viewModelType) as ViewModelBase;
page.BindingContext = viewModel;

if (CurrentApplication.MainPage is NavigationPage navigationPage) // This is true
{
    await (page.BindingContext as ViewModelBase).InitializeAsync(navigationData);
    await navigationPage.PushAsync(page);
}

Now the OnElementPropertyChanged gets called during the page.BindingContext = viewModel;, by which time the bindingcontext's InitializeAsync hasn't been called. I could await the InitializeAsync before setting the view's BindingContext, but then when the application starts up an exception is thrown because the first page isn't set up yet (because of delay waiting to set it up)-"NSInternalInconsistencyException Reason: Application windows are expected to have a root view controller at the end of application launch". How is this usually resolved? I can't imagine it's unusual having a requirement to wait for bindings to complete on the first page of an application? Does everyone just have a dummy static page that requires no bindings or something?

Thanks in advance :smile:


Unable to change ListView.ItemTemplate in code behind in iOS of a Xamarin.Forms app

$
0
0

First I thought it was due to ToolbarItem with Order="Secondary" was not functional in iOS. Unfortunately I didn't put breakpoint and debugged it when I posted the above thing.

But after putting the breakpoint and debugging I found that the setting ItemTemplate in an event was not effective. The pros may tell me if it is a bug.

First, the postings by @NMackay and @ClintStLaurent in this thread confirmed that the way that I was accessing the StaticResource in the code is correct.

Then I found this post on StackOverflow which hinted me what may be wrong. It was mentioned that one has to refresh the ListView several times before the chanted ItemTemplate is effective. And I found that I will have to pull-to-refresh as many times as the number of rows visible. Still the new Itemtemplate is not applied to the top most item.

My code is as below:

    <ContentPage.Content>
        <StackLayout>
            <ListView x:Name="ItemsListView"
                      ItemsSource="{Binding ToDoPlusItems}"
                      VerticalOptions="FillAndExpand"
                      HasUnevenRows="true"
                      RefreshCommand="{Binding LoadItemsCommand}"
                      IsPullToRefreshEnabled="true"
                      IsRefreshing="{Binding IsBusy, Mode=OneWay}"
                      CachingStrategy="RecycleElement"
                      ItemTemplate="{StaticResource ItemTemplateNonFramed}">
                <ListView.GestureRecognizers>
                    <TapGestureRecognizer Tapped="GstrDoubleTapListItem_Tapped"
                                          NumberOfTapsRequired="2" />
                </ListView.GestureRecognizers>
            </ListView>
        </StackLayout>
    </ContentPage.Content>


        <ToolbarItem Text="Show Abridged"
                     Clicked="ShowAbridged_Clicked"
                     Order="Secondary" />
        <ToolbarItem Text="Show More"
                     Activated="ShowMore_Clicked"
                     Order="Secondary" />


        private void ShowAbridged_Clicked(object sender, EventArgs e)
        {
            ItemsListView.ItemTemplate = (DataTemplate)this.Resources["ItemTemplateNonFramed"];
        }

        private void ShowMore_Clicked(object sender, EventArgs e)
        {
            var template = this.Resources["ItemTemplateFramedShort"] as DataTemplate;
            ItemsListView.ItemTemplate = template;
        }

Qunsuo PDA 3505 sdk

$
0
0

Anyone able to access the qunsuo pda 3505 thermal printer and the scanner with xamarin form app ?

How to solve System.FormatException: Index (zero based) must be greater than or equal to zero

$
0
0



above is my code .Why i am getting Exception(System.FormatException:) .Please any one suggest?

How to Implement webView Rendering and pass data in UWP ?

$
0
0

Can any one suggest me how to implement webview Rendering in UWP xamarin.forms .
Thanks in Advance.

Modularity in Xamarin.Forms

$
0
0
The company I'm currently working at has a product with a few core functionalities (forms), that can be accessed by a kind of main menu. Now I'm trying to implement customer specific functionalities with some kind of modules, so this can be developed (and later loaded) only for this specific customer. The key problem is, that we want to develop the customer specific modules in separate solutions/repositories and have our core product load them later, but only the ones that are activated for the specific customer.

Is something like this possible in any way or absolutely not?

How to solve Newtonsoft.Json.JsonReaderException:

$
0
0

I am adding some data to API. But I am getting an error Newtonsoft.Json.JsonReaderException: ..
While debugging in response variable I am getting {StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Cache-Control: no-cache, private
Connection: close
Content-Type: text/html; charset=UTF-8
}}
As i am getting response in html format instead of json . I am unable to deserialize....Any suggestion plz.. where I am doing wrong?

public class StatusView
{
public string status { get; set; }
}

class AddBillFun
{
    public async static Task<StatusView> AddBillData(string transaction_date1, string billing_date1, string vehicle_id1, string customer_id1, string fuel_id1
                                               , string fuel_unit_id1, string fuel_price_id1, string price_per_unit1, string quantity1, string amount1
                                               , string recieved_amount1, string advanced_amount1, string net_amount1, string _status1, string station_id1)
    {

        StatusView statusCheck = new StatusView();
         Uri uri = new Uri(Constants.Bills_URL);
        var postData = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("transaction_date",transaction_date1),//"2018-10-05 12:16:11"
                new KeyValuePair<string, string>("billing_date",billing_date1 ),//"2018-10-05"
                new KeyValuePair<string, string>("vehicle_id",vehicle_id1),//"1"
                new KeyValuePair<string, string>("customer_id", customer_id1),//"1"
                new KeyValuePair<string, string>("fuel_id",fuel_id1),//"1"
                new KeyValuePair<string, string>("fuel_unit_id",fuel_unit_id1 ),//"1"
                new KeyValuePair<string, string>("fuel_price_id",fuel_price_id1 ),//""
                new KeyValuePair<string, string>("price_per_unit",price_per_unit1 ),//"70"
                new KeyValuePair<string, string>("quantity", quantity1),//"10"
                new KeyValuePair<string, string>("amount",amount1 ),//"700"
                new KeyValuePair<string, string>("received_amount",recieved_amount1 ),//"0"
                new KeyValuePair<string, string>("advance_amount", advanced_amount1 ),//"0"
                new KeyValuePair<string, string>("net_amount",net_amount1 ),//"700"
                new KeyValuePair<string, string>("status",_status1 ),//"success"
                new KeyValuePair<string, string>("station_id",station_id1 )//"1"

            };

        HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, uri);
        req.Content = new FormUrlEncodedContent(postData);

        using (HttpClient client = new HttpClient())
        {
            var response = await client.SendAsync(req);

            var content = await response.Content.ReadAsStringAsync();

            statusCheck = JsonConvert.DeserializeObject<StatusView>(content);
        }

        return statusCheck;

    }
}

Bottom Navigation bar in MasterDetailPage

$
0
0

I am using 3rd party xamarin development template and need to create a bottom navigationbar in page bottom.
Please help !!!


How can I refresh a page?

$
0
0

Greetings, I am starting in xamarin forms and I have the following problem
I have two pages page1 and page2 of type NavigationPage, on page1 I show a series of data and information to the user and I can go with a button to page2 which is a kind of form that the user can fill out but when filling in some fields on page1 they should be updated the doubt is the following how can I refresh the page1 from page2? , on page1 I have a function that refreshes the fields that I want to update by printing these changes on the screen. Is it possible to call that function from page2? I try to do the static function but I get an error in the elements of the xaml on page1 that I want to change
Another question I have is why, if I surf, do I have a lot of navigation from page1 to page2 and vice versa does the app end?
to go from page1 to page2 use:
await ((NavigationPage) this.Parent) .PushAsync (new Page2 ());

and to go from page2 to page1 use:
await ((NavigationPage) this.Parent) .PushAsync (new Page1 ());

ActivityIndicator in Stacklayout show error with Invalid arguments

$
0
0

Dear All.
I am new to this forum and I don't know how to post question. I opened discusstion also for this and again I am asking this question.

Please help me in this regards. I get following error in .cs file when I add ActivityIndicator to Stacklayout.
It shows me red line with msg Argument 1: cannot not convert from .ActivityIndicator to Xamarin.Forms.Views.
Below is my code
ActivityIndicator ai = new ActivityIndicator() { IsVisible = true };
StackLayout sl = new StackLayout() {
Spacing = 0,
Margin = new Thickness(0, 0, 0, 0),
Padding = new Thickness(0, 0, 0, 0),
Children = { ai, periodgrid } // error here. Red line appears under ai
};
Thanks and best regards,

WebView HtmlWebViewSource crashing the app

$
0
0

Hello,

I want to display html text using webview. Currently I am testing it on UWP. Problem is whenever I use WebView in my current XAML code it's crashes the app and throw exception on the last page. I even tried using some hard quote value but even that's not working.

My XAML Code:

<ContentPage.Content>

        <Image x:Name="ProductDetailsImage" WidthRequest="200" HeightRequest="200"></Image>
        <Label x:Name="ProductDetailsName" ></Label>
        <Label x:Name="ProductDetailsStartingFrom" ></Label>
        <Label x:Name="ProductDetailsBrand" ></Label>
        <Label x:Name="ProductDetailsSKU" ></Label>
        <Label x:Name="ProductDetailsMPN" ></Label>
        <Label x:Name="ProductDetailsStockStatus" ></Label>
        <Label x:Name="ProductDiscontinued" Text="Non-Returnable" IsVisible="False" ></Label>

        <Picker x:Name="SelectColorPicker" ItemDisplayBinding="{Binding name_str}" 
                SelectedItem="{Binding option_value_id}" IsVisible="False" Title="Select Color:"
                SelectedIndexChanged="SelectColorPicker_SelectedIndexChanged"></Picker>

        <Picker x:Name="SelectSizePicker" ItemDisplayBinding="{Binding name_str}"
                SelectedItem="{Binding option_value_id}" IsVisible="False" Title="Select Size:" 
                SelectedIndexChanged="SelectSizePicker_SelectedIndexChanged"></Picker>

        <Label Text="Enter Quantity: " x:Name="LabelQty" IsVisible="False"></Label>
        <Entry x:Name="ProductQty" Text="1" IsVisible="False"></Entry>
        <Button x:Name="AddToCart" Text="Add to Cart" IsVisible="False" Clicked="AddToCart_Clicked"></Button>
        <Button x:Name="AddToWishlist" Text="Add to Wishlist" IsVisible="False" Clicked="AddToWishlist_Clicked"></Button>     


        <WebView HeightRequest="100" WidthRequest="100">
            <WebView.Source>
                <HtmlWebViewSource x:Name="ProductHtmlWebViewSource"></HtmlWebViewSource>
            </WebView.Source>
        </WebView>

    </StackLayout>
</ContentPage.Content>

Code Behind:

ProductHtmlWebViewSource.Html = product.data.descriptions;

Any help would be appreciated.

Thank you

Xamarin.uitest backdoor method to take picture

$
0
0

Our app uses the native device camera does anyone have a backdoor method to access and take picture?

So I have been scouring the internet for the past couple of days and have yet to find a resolution. I have "ideas" on what I need to do but am stumped. Our app relies heavily on taking pictures. I understand that the UITest isn't able to interact with the native camera, but has anyone created a backdoor method that will allow the user to either upload a photo as a mock and then interact with the app? Or if there is another solution I am open to hear. This is for xamarin.uitest

Manipulate image for ListView

$
0
0

Hello
I've got a problem. I want to have some kind of dynamic icon for my ListView items. Means: I want to create that icon programatically at runtime.

Therefore I need the following:
1. Load an ong from file
2. place text on that file
3. place another png-symbol in a specific area of that image
4. save that image to disk
5. path to imagesource

Sounds easy, but seems to be not as easy at Xamarin, is it?

Possible to disable caching in WebView?

$
0
0
I need to be able to disable caching from the WebView, is that possible to do in Forms or even with a custom renderer?

[iOS] need guidance:: ! skia sharp in pcl or custom renderer for printing drawings in canvas !!

$
0
0

Hello guys :) , I have a XF project (pcl, ios, and android), also I'm using Skiasharp graphic library for rendering geometric shapes on the screen and its working fine using xaml and code behind, The issue is I want to print the drawing i need custom renderer and i dont know if i can use skia sharp again for drawing the pdf because skia objects are not compatible with ios! should I draw everything in native way (custom renderer) and give up on skia? or there is a way to do it?
Thanks!!

// class

class Printer : IPrintCreator
{
public bool Create(NoteType type, string filePath)
{
try
{
var printInfo = UIPrintInfo.PrintInfo;
printInfo.OutputType = UIPrintInfoOutputType.General;
printInfo.JobName = "Print PDF Sample";

            //var height = 1754;
            //var width = 1240;
            //CGSize pageSize = new CGSize(width, height);

            NSMutableData pdfData = new NSMutableData();

            try
            {
                UIGraphics.BeginPDFContext(pdfData, view____here??????????????????????????????????????????????????, null);
                UIGraphics.BeginPDFPage();
                var pdfContext = UIGraphics.GetCurrentContext();

                PrintContentPageRenderer.pview.Layer.RenderInContext(pdfContext);

                UIGraphics.EndPDFContent();



                var printer = UIPrintInteractionController.SharedPrintController;
                printInfo.OutputType = UIPrintInfoOutputType.General;
                printer.PrintingItem = view____here??????????????????????????????????????????????????;
                printer.PrintInfo = printInfo;
                printer.ShowsPageRange = true;

                printer.Present(true, (handler, completed, err) => {
                    if (!completed && err != null)
                    {
                        Console.WriteLine("error");
                    }
                });
            }
            catch (Exception ex)
            {
                //     The error domain that the printing system uses to report errors.
                var error = UIPrint.ErrorDomain;
            }

            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

Modularity in Xamarin.Forms

$
0
0
The company I'm currently working at has a product with a few core functionalities (forms), that can be accessed by a kind of main menu. Now I'm trying to implement customer specific functionalities with some kind of modules, so this can be developed (and later loaded) only for this specific customer. The key problem is, that we want to develop the customer specific modules in separate solutions/repositories and have our core product load them later, but only the ones that are activated for the specific customer.

In know something like this can for example be done with Prism, but only in Wpf. Therefore I posted this in this forum, cause I need this for Xamarin.Forms.

Is something like this possible in any way or absolutely not?

Error message:Project Android.Common is not compatible with netstandard2.0

$
0
0

In my project I have a strange error message:
Project Android.Common is not compatible with netstandard2.0 (.NETStandard,Version=v2.0). Project Android.Common supports: monoandroid81 (MonoAndroid,Version=v8.1)
I use Visual Studio 15.9.5 and Xamarin.Forms 3.4.0.1009999 in the project
I don't have any idea how I can resolve.

Any ideas ?

How to I change the selected text color of Hamburger item

$
0
0

i want to change the text color of selected item in MAster detail page???

Toolbaritems, I have set font awesome text icon, it's not display in iOS.

$
0
0

I have set Font awesome icon in Text of Toolbaritems, It was working properly.
But after set Navigation bar Property using : On<Xamarin.Forms.PlatformConfiguration.iOS>().EnableTranslucentNavigationBar();
For Transparent Navigation bar, but now Icons are not displaying, Question mark shows.

How to Customise the pop up of picker into Dropdown list

$
0
0

Hi,
I want to customise the picker pop up into drop down list (In Android)

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>