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

Using declarative style C# instead of XAML - should Xamarin redirect XAML efforts elsewhere?

$
0
0

Introduction

Miguel tweeted:
"I should have never added Xaml and instead invented our own ...", expressing regrets about having to deal with XAML (standardization) problems.

My response was:
"I would applaud dropping XAML altogether. Advancements in C# (declarative syntax) have eliminated any advantages of a separate markup language for years. Why would you want to hand-code an object serialization format? Why waste time on duplicating dev tools for features that c# already offers?"

David expressed an interest to see how I have been creating Xamarin Forms markup in declarative style C#, instead of in XAML, for the past few years. So I write this post to provide a concrete example, and share the reasoning behind my remark (which was deliberately lacking nuance - it is Twitter after all).

Redirecting Xamarin IDE team effort

Why do I spend time on this? In the past years I only experienced advantages from using declarative C# instead of XAML. Given that the core challenge for the Xamarin IDE teams remains to improve the developer productivity, I would love to see some of the effort now being spent on (imo redundant) XAML tooling to be redirected towards reducing IDE bugs and speeding up the dev cycle, i.e. Live Player.

I recently investigated Google's Flutter (build beautiful native apps in record time), which by design has no separate language for markup and which offers hot reload - which is like a Xamarin Live Player without any limitations and a refresh time of 400-600 ms (I checked on devices and emulators). This is what I want from Xamarin!

This is the competition Xamarin is facing today. Some developers are already switching from Xamarin to Flutter because of developer tooling productivity, which apparently can be more important than language or framework or experience. As a Xamarin veteran, I get why they do this. I feel that unless there is a significant team increase, Xamarin needs to focus and redirect existing effort towards developer productivity, meaning less IDE bugs and faster development cycle.

Example
.
Here is an unabridged example of a simple registration code page in a production app I wrote:

Content = new Grid { 
    RowSpacing = 0, 
    RowDefinitions = { new RowDefinition { Height = GridLength.Auto }, new RowDefinition {}},
    Children = {
        PageHeader.Create(PageMarginSize, nameof(vm.RegistrationTitle), returnToPreviousViewCommandPropertyName: nameof(vm.CancelEnterRegistrationCodeCommand), centerTitle:true),

        new ScrollView { Content = new Grid {
            RowDefinitions = {
                new RowDefinition { Height = 170 },

                new RowDefinition { Height = 75 },
                new RowDefinition { Height = GridLength.Auto },
                new RowDefinition { Height = GridLength.Auto }
            },
            RowSpacing = 0,

            ColumnDefinitions = {
                new ColumnDefinition { Width = 160 },
                new ColumnDefinition { }
            },

            Children = {
                new Label {
                    Margin = fieldNameMargin, LineBreakMode = LineBreakMode.WordWrap, 
                    HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.Center, HorizontalTextAlignment = TextAlignment.Center, 
                }.SetFontSize(WspFontSizes.Size15)
                 .SetColRow(0, 2, 0, 1)
                 .Bind(nameof(vm.RegistrationPrompt)),

                new Label { Text = "Registration code", VerticalOptions = LayoutOptions.End, Margin = fieldNameMargin }.SetFontSize(WspFontSizes.Size13)
                .SetColRow(0, 1, 1, 2),
                new Label { HorizontalOptions = LayoutOptions.End, VerticalOptions = LayoutOptions.End, Margin = fieldNameMargin }.SetFontSize(WspFontSizes.Size13)
                .SetColRow(1, 2, 1, 2)
                .Bind(nameof(vm.RegistrationCodeValidationMessage)),

                new Entry {
                    Placeholder = "E.g. 123456", HeightRequest = 44, Keyboard = Keyboard.Numeric, 
                    BackgroundColor = WspColors.White.ToColor(), TextColor = WspColors.Gray1.ToColor(), Margin = fieldMargin }.SetFontSize(WspFontSizes.Size15)
                .Bind(nameof(vm.RegistrationCode), BindingMode.TwoWay)
                .Id(AId.RegistrationCodePage_CodeEntry)
                .SetColRow(0, 2, 2, 3),

                new Button {
                    Text = "Verify",
                    Margin = PageMarginSize,
                    HeightRequest = 44,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    TextColor = WspColors.White.ToColor(),
                    BackgroundColor = WspColors.ColorValueAccent.ToColor()
                }.SetFontSize(WspFontSizes.Size13)
                 .Id(AId.RegistrationCodePage_VerifyCodeButton)
                 .Bind(Button.IsVisibleProperty, nameof(vm.CanVerifyRegistrationCode))
                 .Bind(nameof(vm.VerifyRegistrationCodeCommand))
                 .SetColRow(0, 2, 3, 4),
            }
        }}.SetColRow(0, 1)
     }
 };

Nothing advanced is going on here, I use standard C# language features to reuse controls (e.g. PageHeader.Create method ) and to simplify data binding (.Bind extension methods). In my eyes the above reads similar to equivalent XAML.

Which is not very surprising given that XAML is at its heart just an object serialization format in XML. In other words, XAML does what the new keyword in C# does.

Now, C# is designed for humans; while XML is better for tools such as visual designers. As a matter of fact, that was the vision for (WPF) XAML: that human designers could use a tool (Blend) to create a UI that developers could consume. However, I experienced how that vision, even in the best possible time and scenario, failed to deliver (I Built a WPF app for Windows tablet together with a XAML book authoring, leading designer, who was a master in Blend, when that was THE tool. The UI was beautiful and totally unmaintainable). So even if there would come an ultimate visual designer tool for Xamarin Forms, equivalent to the best that Blend ever was, it would still fail for the same reasons. Time to move on, like Flutter?

So, anyone (Xamarin devs and Xamarin team) wants to chime in on either XAML versus C# or redirecting Xamarin IDE efforts?
I'm really curious how Xamarin devs (especially experienced ones) see this.

Thanks!


Master/Detail PushAsync

$
0
0

Hi to all.
I followed this https://youtube.com/watch?v=UBqdI77_p-M tutorial which is for Master/Detail.
I create the pages an I can see the menus in the drawer. I add a ItemSelected event but when I tried to PushAsync to my new page an error appear which says that "PushAsync is not supported globally n android".
I tried to change my MainPage as NavigationPage, but a "header" appear in the screen. Is possible to PushAsync or I should use PushModalAsync instead.
How he did it in the youtube tutorial?
Thanks in advance.

Getting avlist view to work in apple but it works great in Android, how do I get it to work in both

$
0
0

Hi all,

I have an couple of issues... the app looks great in android but it looks like feathers on apple.

Some of my issues... the app background image does not look good in apple... is there a way to remove it apple but keep it in Android.
The buttons in apple are not buttons...just text but in Android they look like buttons and are readable.

and there there is the list view thing... I need to display a list that has multiple rows...

My code that I have posted works great in Android... but looks a mess in apple.

blow is the code... can any one provide some guidance?

Thank you.

<?xml version="1.0" encoding="utf-8" ?>

<ContentPage.Content>

        <ListView x:Name="SomeDetailsListView"  SeparatorVisibility="Default" RowHeight="120"> 

            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Vertical">
                                <Label Text=""/>

                            <Label  Text="{Binding row1, StringFormat='row Info text1 = {0:N}'}"/>
                            <Label  Text="{Binding row2, StringFormat='row Info text1  = {0:N}'}"/>
                            <Label  Text="{Binding row3, StringFormat='row Info text1  = {0:N}'}"/>
                            <Label  Text="{Binding row4, StringFormat='row Info text1  = {0:N}'}"/>
                            <Label  Text="{Binding row5, StringFormat='row Info text1  = {0:N}'}"/>
                            <Label  Text="{Binding row6, StringFormat='row Info text1  = {0:N}'}"/>
                            <Label  Text="{Binding row7, StringFormat='row Info text1  = {0:N}'}"/>

                        </StackLayout>
                    </ViewCell>

                </DataTemplate>

            </ListView.ItemTemplate>
        </ListView>

    </StackLayout>
</ContentPage.Content>

The case for .NET Standard in favour of shared project for Xamarin.Forms

$
0
0

There is a bunch of information online about using .NET Standard for your Xamarin.Forms app, but I'm still confused as to why you would want to use one over the other. The main sources I have read through/watched:
1. Sharing Code Overview (MS docs)
2. .NET Standard 2.0 Support in Xamarin.Forms
3. .NET Standard and Xamarin.Forms for the .NET Developer

My history is I've been a Xamarin developer since the Novell days. Since the introduction of Xamarin.Forms (1.5ish?) I've always used it for creating apps over Xamarin.iOS and Xamarin.Android directly. I've never created a Forms app with PCL, always shared library. One thing I've relied heavily on is the ability to just go:

#if __IOS__
    UIApplication.SharedApplication.StatusBarHidden = true;
#elif __ANDROID__
    // Other things.
#endif

Being able to do this in the Forms code directly has made things nice and easy. Another example I have used it is in in my own HTTP REST classes, and the ability to use cookie containers in certain ways that would work on both platforms (bugs that may have been resolved now). I now know that in the first example I could create a dependency service called StatusBarActions or something. The second example I know now not to re-invent the wheel and I could just use RestSharp. It's just that one of the listed benefits of using shared code is the ability to use those pre-processor directives.

Likewise two of the main pros of .NET Standard are "Allows you to share code across multiple projects." and "Refactoring operations always update all affected references.". But wouldn't this still be true for a shared Forms app?

Lately I was playing around with converting some smaller in progress apps to be .NET Standard Forms apps. I really enjoy the simplicity of having my main NuGet packages (Xamarin.Essentials, Json.NET, FFImageLoading, sqlite-net-pcl, etc) in the Forms project itself. Its really nice to be able to update all packages at once. The package list also stays nice and short, although I think that's more to do that it doesn't list all package dependencies as new packages. I also liked that it forced me to write cleaner code. Things were good... until I tried Xamarin.Forms on macOS.

Although it is still in preview one of the first things I found that out of the box Xamarin.Essentials was not having a bar of it. It's just one of many packages that may not be supported. It made me think of another project I am working on, Onewheel Community Edition App. It relies heavily on the Plugin.BLE NuGet package that doesn't support macOS or UWP. If I wanted to add either of those platforms I now have to add it via a dependency service or something similar. Alternatively if I used a shared project I could just have a

#if __IOS__ OR __ANDROID__ etc. 

I can see both being possible. One makes it easier when a core component is platform specific, but can also make it more of a pain in the case of Xamarin.Essentials when you may just want to use it to display the app version number.

So the real things I want to know are:

  • Is it worth it?
  • Are there any performance benefits of either?
  • Are there binary size or binary security differences that are worth noting.

What are other peoples experience with it shared vs .NET Standard. Are there some other programming paradigms that I am not thinking of to make .NET Standard apps make more sense?

Read pixel data of Image in Xamarin Forms

$
0
0

Hi Team,
I am looking to get help on converting Image to 3D byte array, reading its RGB values
This code works fine on my .Net platform, but with Xamarin I have trouble getting Color and Bitmap class working together. Could someone help me get an equivalent code for Xamarin platform ?

    byte[] imageData = new WebClient().DownloadData(imurl);
                MemoryStream imgStream = new MemoryStream(imageData);
                curr_img = Image.FromStream(imgStream);
                Bitmap bmp = new Bitmap(curr_img);

                int wSize = curr_img.Width;
                int hSize = curr_img.Height;

                image_inlist = new List<List<List<int>>>(); 
                for(int i=0; i < hSize; i++)
                {
                    List<List<int>> eachrow = new List<List<int>>();
                    for(int j=0; j<wSize; j++)
                    {
                        Color clr = bmp.GetPixel(j, i);
                        eachrow.Add(new List<int> {clr.R,clr.G,clr.B});

                    }
                    image_inlist.Add(eachrow);
                }

modify image pixels in forms

$
0
0

Hi I want to change a collared image to greyscale before I show it on the screen. Can some one please tell me why my code below is not working?

     private byte[] ConvertMediaFileToByteArray(MediaFile file)
        {
            using (var memoryStream = new MemoryStream())
            {
                file.GetStream().CopyTo(memoryStream);
                return memoryStream.ToArray();
            }
        }

        public void LoadAndConvertImage(MediaFile imgPath){
            byte[] imgSrc = ConvertMediaFileToByteArray(imagePath);
            ConvertToGrayRemoveNoise(ref cropedBytes);

             ImageSource imageSource = ImageSource.FromStream(() =>
            {
                var cropedImage = new MemoryStream(cropedBytes);
                file.Dispose();
                return cropedImage;
            });
            Image Image.Source = imageSource;

        }
        public void ConvertToGray(ref byte[] srcPixels)
        {
            try
            {
                for (int i = 0; i < srcPixels.Length; i += 4)
                {
                    double b = (double)srcPixels[i] / 255.0;
                    double g = (double)srcPixels[i + 1] / 255.0;
                    double r = (double)srcPixels[i + 2] / 255.0;

                    byte a = srcPixels[i + 3];
                    //convert to gray
                    double e = (0.299 * r + 0.587 * g + 0.114 * b) * 255;

                    byte f = Convert.ToByte(e);

                    srcPixels[i] = f;
                    srcPixels[i + 1] = f;
                    srcPixels[i + 2] = f;
                    srcPixels[i + 3] = a;

                }
            }
            catch (Exception error)
            {
                Debug.WriteLine(error.ToString());
            }
        }

I see two issues. Sometime the ConvertToGray function runs into the Catch with a pointer out of range. If this does not happen the initialisation of the image fails with "initWithData returned nil". I would like to work with the byte[] as several plugins with crop also use that as input and output.

Forms Tabbed Page OnAppearing

$
0
0

I have the following code for tabbed Main page but would like to know why are the OnAppearing method being called on all the tabbed pages on first run of the App. Is there a way to only run the OnAppearing then the Tab is the active one ?

TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" 
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
            xmlns:local="clr-namespace:MyApp.View;assembly=MyApp"
            x:Class="MyApp.View.MainTabbedPage" 
            xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
            android:TabbedPage.ToolbarPlacement="Bottom"

            BarBackgroundColor="#4caf50"
            BarTextColor="White"
            android:TabbedPage.IsSwipePagingEnabled="False"
            android:TabbedPage.BarItemColor="#66FFFFFF"
            android:TabbedPage.BarSelectedItemColor="White" >

    <TabbedPage.Children>
        <NavigationPage x:Name="DeviceNavPage" 
                        Title="Devices" 
                        Icon="devices" 
                        BarBackgroundColor="#4caf50" >
            <x:Arguments>
                <local:DevicePage />
            </x:Arguments>
        </NavigationPage>
        <NavigationPage x:Name="SharingNavPage" 
                        Title="Sharing" 
                        Icon="share" 
                        BarBackgroundColor="#4caf50" >
            <x:Arguments>
                <local:SharingPage/>
            </x:Arguments>
        </NavigationPage>
        <NavigationPage x:Name="SettingNavPage" 
                        Title="Settings" 
                        Icon="settings" 
                        BarBackgroundColor="#4caf50" >
            <x:Arguments>
                  <local:SettingPage/>
            </x:Arguments>
        </NavigationPage>


    </TabbedPage.Children>

</TabbedPage> 

size of screen

$
0
0

Hello,
Is it possible with xamarin forms, for Android and IOS, to know the size of the screen on which the application is launched?
Thank you for your answers.
YC


Question related to xamarin and string formating in a listview.. My output is not changing

$
0
0

Hi all I have only tested this part in apple and not in Android just yet...
But Iam trying to format my output in my list to be just a date value and no time and another field to be both date and time but with the letter 'T' removed...

I see items in c# that I tried but my xamarin ouput does not change.

Here is what I have:

<Label  Text="{Binding LAST_UPDATE, StringFormat='Date Updated = {0:MM/dd/yy HH:mm:ss}'}"/>

The output I get is 2018-12-17T00:00:00
I would like the output to be 12/17/2018

<Label  Text="{Binding LAST_USEAGE_DATE, StringFormat='Last Used = {0:MM/dd/yyyy}'}"/>

The output I get is 2018-12-17T20:10:507

I would like the output to be 12/17/2018 20:10

These items are in a list view... the data comes from a sql database that uses datetime
but I was hoping that I could format them via the application but nothings seems to work
when the page renders on the phone sadly (right now testing with apple simulator)
Will test with Android again after I get things ironed out in apple...so my fingers ae crossed.

Thanks in advance!

Failure [INSTALL_FAILED_VERSION_DOWNGRADE], can not deploy Android app

$
0
0

Hello, in my solution, I can not run the project on my Android phone. Can not deploy the solution because of the error : Failure [INSTALL_FAILED_VERSION_DOWNGRADE]. How can I solve it?

What is default height of navigation bar ?

$
0
0

Hello,

I was wondering what is the default height of navigation bar ? Something like 15% of the screen ?
I would like to manually reproduce a navigation bar on a modal page, with the same size than the default navigation bar.

Thanks.

How to catch home button click in xamarin forms page

$
0
0

Hi Team,

Is there any way to catch home button click event in xamarin form page ?

Thanks,
Mahesh K

Tap on map to get location Xamarin.forms.Maps

$
0
0

I did implement maps in Xamarin Forms following this instructions but now I need to get the location when the user tap on the map.

I did see that is necessary to create a custom control to do that, but, I can't find a good solution to reach that.

I am testing only in Android.

MapGoogle.xaml

<maps:Map WidthRequest="320" HeightRequest="200"
              x:Name="MyMap"
              IsShowingUser="true"
              MapType="Street"/>

MapGoogle.xaml.cs

 public MapGoogleView(double lat, double lon)
        {
            try
            {
                InitializeComponent();
                NavigationPage.SetHasNavigationBar(this, false);
var map = new Map(
                MapSpan.FromCenterAndRadius(
                        new Position(lat, lon), Distance.FromMiles(0.3)))
                {
                    IsShowingUser = true,
                    HeightRequest = 100,
                    WidthRequest = 960,
                    VerticalOptions = LayoutOptions.FillAndExpand,
                    MapType = MapType.Street
                };
                var stack = new StackLayout { Spacing = 0 };
                stack.Children.Add(map);
                Content = stack;

var position = new Position(lat, lon); // Latitude, Longitude
                var pin = new Pin
                {
                    Type = PinType.Generic,
                    Position = position,
                    Label = "Ubicación",
                    Address = "Latitud: " + lat.ToString() + ", Longitud: " + lon.ToString(),
                };
                MyMap.Pins.Add(pin);
                map.MoveToRegion(
                MapSpan.FromCenterAndRadius(
                new Position(lat, lon), Distance.FromMiles(1)));
}

Xamarin.Forms 3.0.0.482510
Xamarin.Forms.Maps 3.0.0.482510

What is the best way to get that?

Thanks in advance.

Can we show Same Date Pikcker UI for iOS and Android instead of default iOS date picker

$
0
0

I want to show Android date time picker dialog in iOS instead of iOS native date picker. Will I able to do it ?

I need to Implement a Search option for Dropdown...How to do

$
0
0

When i Select an item in dropdown1. it need to search for similar items (similar text) in the table and need to bind that items to Dropdown2

How to implement this..
if any please help
im Struct in this

Thanks in advance


My Android Emulator has a white background. Why?

$
0
0

I noticed that in the Xamarin.Forms book Im currently reading the author uses examples of Android Emulators which all have a dark background. It should be a default Color.

Also when Im looking at my Android Emulator Preview I see a dark background.

But when Debugging the background of my Android Emulator is light. Why? Is it a bug? Is there something wrong in my settings?

How much Xamarine Forms application vary with enviornment

$
0
0

In the learning video of Xamarine Forms it is mentioned that Xamarine Forms application is not pixel perfect can any one please show me the UI comparison of Xamarine forms application in different environment

Can not add Xamarin.Essentials.

$
0
0

Hi

When i try to add Xamarin.Essentials package to Xamarin.Android project i am getting following error. Can any one tell me how can i resolve this error.

Error:
Severity Code Description Project File Line Suppression State
Error NU1107 Version conflict detected for Xamarin.Android.Support.Compat. Reference the package directly from the project to resolve this issue.
MyProject.Android -> MyProject -> Xamarin.Essentials 1.0.0 -> Xamarin.Android.Support.Core.Utils 26.1.0.1 -> Xamarin.Android.Support.Compat (= 26.1.0.1)
MyProject.Android -> Xamarin.Android.Support.CustomTabs 25.4.0.2 -> Xamarin.Android.Support.Compat (= 25.4.0.2).

Thanks.

How to add images only to the last three items of the listview?

$
0
0

** I want to add the images to the specific items of the listview.** not for all collection in the listview

Animated Splash Screen: How to transition to MainActivity

$
0
0

Hi,

I have two activities (SplashActivity, MainActivity) that i am trying to transition between but i get a black screen, and what seems like a complete restart, between them.

The reason i'm using a second activity for the splash screen is for an animation.

Is there a way to start loading the MainActivity while the SplashActivity displays its animation? As it currently stands, MainActivity only begins after the SplashActivity, defeating the whole purpose.

Code snippets of the 2 activities below:

SplashActivity

[Activity(Label = "IFS.Mobile", Icon = "@mipmap/icon", Theme = "@style/SplashTheme",
    NoHistory = true,
    MainLauncher = true,
    ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
  public class OnboardingWithCenterAnimationActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
  {
    public static int STARTUP_DELAY = 300;
    public static int ANIM_ITEM_DURATION = 1000;
    public static int ITEM_DELAY = 300;
    static readonly string TAG = "X:" + typeof(OnboardingWithCenterAnimationActivity).Name;

    private bool animationStarted = false;
    protected override void OnCreate(Bundle savedInstanceState)
    {
      base.OnCreate(savedInstanceState);
      Log.Debug(TAG, "SplashActivity.OnCreate");
      SetContentView(Resource.Layout.activity_onboarding_center);

      Task.Run(() =>
      {
        Log.Debug(TAG, "Pausing Thread");
        Thread.Sleep(2000);

        RunOnUiThread(() => {

          Log.Debug(TAG, "Starting MainActivity");
          StartActivity(typeof(MainActivity));

        });
      });
    }

    // Prevent the back button from canceling the startup process
    public override void OnBackPressed() { }

    public override void OnWindowFocusChanged(bool hasFocus)
    {

      if (!hasFocus || animationStarted)
      {
        return;
      }

      animate();

      base.OnWindowFocusChanged(hasFocus);
    }

MainActivity

       [Activity(Label = "IFS.Mobile", Icon = "@mipmap/icon", Theme = "@style/MainTheme",
         ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
        public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
          {
            protected override void OnCreate(Bundle bundle)
            {    
              base.OnCreate(bundle);

              // Initialize Xamarin Forms engines.
              Xamarin.Forms.Forms.Init(this, bundle);
              CrossCurrentActivity.Current.Init(this, bundle);

              TabLayoutResource = Resource.Layout.Tabbar;
              ToolbarResource = Resource.Layout.Toolbar;

              LoadApplication(new App(new AndroidPlatformInitializer()));
            }
         }
Viewing all 91519 articles
Browse latest View live