BenkoBlog

Confessions of an Evangelist

Issue with Xamarin Forms - InitializeComponent does not exist - Xamarin XAML is not Windows XAML

Originally posted on: http://geekswithblogs.net/benko/archive/2015/02/02/issue-with-xamarin-formsndashinitializecomponent-does-not-exist-xamarin-xaml-is-not.aspx

Have you ever tried to reuse code by adding existing files to a project? In Visual Studio this usually works, with the file getting put into the right location, associating the editor based on the file extension. I’ve been working on a Xamarin Forms project which allows me to use XAML to create the UI and C# for the code behind. This enables me to leverage my skills and experience building Windows and Windows Phone applications on iOS and Android. The problem came when I would include an existing file into a project.

image

The error: InitializeComponent does not exist – makes me wonder what’s wrong with the file? First things first, I checked that the namespace and class names matched. Next I tried commenting out what might’ve been invalid XAML syntax with the thought that maybe it wasn’t compiling right. No luck. Finally I compared the file to another that was working (I added myWorkingForm.XAML and guess what, no error in that one!). Both had the same namespace, both had the same class name declared as public partial (meaning it’ll compile the XAML + the C# into a class).

Finally I was down to looking at the compiled objects folder…and I saw that while myWorkingForm created an interim file myWorkingForm.xaml.g.cs the one that came from the file I included did not. I decided to look at the shared project’s projitems file (which is what lists the types of files in the project). I discovered that Visual Studio assumes that a XAML file is Windows XAML, not Xamarin XAML. In the projitems file the XML showed that adding the existing file associated it as a Page, where the other file that worked was marked as an Embedded resource (see below).

<ItemGroup>
  <EmbeddedResource Include="$(MSBuildThisFileDirectory)Pages\myWorkingForm.xaml">
    <SubType>Designer</SubType>
    <Generator>MSBuild:UpdateDesignTimeXaml</Generator>
  </EmbeddedResource>
</ItemGroup>

<ItemGroup>
  <Page Include="$(MSBuildThisFileDirectory)Pages\TestForm.xaml">
    <SubType>Designer</SubType>
    <Generator>MSBuild:Compile</Generator>
  </Page>
</ItemGroup>

To make it work? Manually change the myproject.projitems file (in the solution explorer open the containing folder then edit the file with notepad) for TestForm.xaml to use the EmbeddedResource tag, matching that for myWorkingForm.xaml. This causes the build to use the Xamarin compiler and generate an interim file TestForm.xaml.g.cs. Problem solved!

Happy Coding!    (originally posted on www.benkotips.com)

Technorati Tags: ,
[More]

Some Common Xamarin.Forms XAML Control Properties

Originally posted on: http://geekswithblogs.net/benko/archive/2014/12/29/some-common-xamarin.forms-xaml-control-properties.aspx

imageXamarin.Forms is an attractive option when building cross platform apps, but for an old XAML developer like myself it can be a challenge to get the nuances of the grammar and syntax right. For Windows I’ve depended on tools like Blend and Visual Studio Intellisense to help me understand what’s possible. Moving to Xamarin XAML is sometimes tedious because while I can use the intellisense from the C# code behind file it’s not there yet in a designer. While there’s some posts out there that compare and contrast how to move to Xamarin XAML from Microsoft XAML (like this one from TCPWare by Nicolò Carandini), I still wasn’t finding what I was looking for. This post is an attempt to iterate thru some of the core proprties of interest for many of the controls I use, and to catalog them here for current and future reference.

1/3/2015 : Update, added more controls to list -

Technorati Tags:

First some common properties – Some common properties to most controls include:

  • x:Name : The control name that can be used to reference the control from code
  • AnchorX, AnchorY : Positions control within the layout
  • HeightRequest, WidthRequest : The requested size of the control if the layout allows
  • MinimumHeightRequest, MinimumWidthRequest : The minimum size allowed
  • HorizontalOptions, VerticalOptions : Layout options for the control, include values Start, End, Fill, Center, StartAndExpand, EndAndExpand, CenterAndExpand
  • BackgroundColor : Color of background
  • Rotation, RotationX, RotationY : Rotation properties for rendering control
  • Scale : Scale value

Label - Displays text on a page.

  • XAlign, YAlign : Text alignment property…values include TextAlignment.Start, TextAlignment.Center, TextAlignment.End
  • TextColor : Color of text and background…can be named color
  • Font : Attributes of the font, such as Bold, Italic, Large, Medium, Small, Micro, 
  • LineBreakMode : Used to determine label’s text wrap properties. Values include CharacterWrap, NoWrap, WordWrap, HeadTruncation, MiddleTruncation, TailTruncation

TextCell - Displays text and detail subtext in a single control

  • Text : The main text to display
  • TextColor : Primary color of the text
  • Detail : Subtext displayed below main text
  • DetailColor : Color of secondary text

imageimageimageBoxView - Similar to Rectangle in Windows XAML. Used to display a box with some color on a page.

  • Color : Color of box
  • Opacity : Value of opacity…
  • IsEnabled, IsFocused : properties of Box

Entry - Similar to TextBox in Windows XAML. Used to get input from user.

  • TextColor : Color of text and background…can be named color
  • IsEnabled, IsFocused, IsPassword, IsVisible : Values that drive entry behaviors
  • InputTransparent : Determines whether to show input
  • Keyboard : Type of keyboard to show, possible values include Chat, Default, Email, Numeric, Telephone, Text, Url
  • Placeholder : Text to display when there is no value entered…displayed in grayed out mode
  • Text : Value of control

Image - Display an image. Includes common properties and:

  • Aspect : Scaling of image…stretch or fill. Values include Fill, AspectFill, AspectFit
  • IsEnabled, IsFocused, IsLoading, IsOpaque, IsVisible : Drive behaviors of image control
  • Source: This is where the image is sourced from…can be local resource or online.

ImageCell Displays an image and a TextCell

  • ImageSource
  • Text, TextColor
  • Detail, DetailColor
  • IsEnabled

Button - Used to trigger event processing in response to user’s actions

  • BorderColor, BorderRadius, BorderWidth : Values to control the border of the button
  • Command, CommandParameter : Values for the command to be executed when clicked
  • Font : Attributes of the font
  • IsEnabled, IsFocused, IsVisible : Values to drive button’s behaviors
  • Text : Text on the button
  • TextColor : Color of text on the button 

ActivityIndicator. An indicator that shows there is an action processing and the user needs to wait for it to complete

  • Color : Color of the indicator
  • IsEnabled, IsFocused, IsRunning IsVisible : Values to drive activity indicator’s behaviors

ProgressBar. Used to display how far along a process is

  • IsEnabled, IsFocused, IsVisible : Values to drive the control’s behaviors
  • Progress : Value to show completion…I think this is a value from 0.0 to 1.0

TimePicker. Used to select a time value

DatePicker. Similar to TimePicker, but used to select a date

  • Date : The date value of the control
  • Format : Format to display, using standard C# formats

Switch. Used to input whether a boolean property is true or false

  • IsToggled, IsEnabled, IsVisible, IsFocused : Drive control’s behaviors

SwitchCell. Displays a label and a switch

  • Text : The text of the label
  • On : A boolean value of whether the switch is toggled
  • Height : The height of the control

ViewCell. A basic layout control that displays an item in a data template. Does not have the basic properties.

  • Height : Height of cell to display

StackLayout. Similar to a StackPanel in Windows XAML, used to display items in a stack. Has the common properties as well

  • Padding : The area around the layout, displayed as an integer or series of values “left, top, right, bottom”… i.e. “20,0,0,0” means left margin of 20, zero on other sides
  • Spacing : The area between items
  • Orientation : Horizontal vs Vertical

Grid. Layout in Columns and Rows, using various spacing options, such as fixed, Auto and Star – *

  • RowDefinitions, ColumnDefinitions : Same as Windows XAML
  • RowSpacing, ColumnSpacing : distance between columns and rows, defaults to 6 px

ListView. Container for collections of items…

  • ItemsSource : The data collection used to populate the list
  • SelectedItem : If an item is selected in the list
  • IsEnabled, IsGroupingEnabled, IsVisible : Drives list’s behaviors
  • RowHeight : Height of item’s row
  • HasUnevenRows : A flag that indicates row height varies
  • Triggers : connects an item to a behavior
  • ItemTemplate : Binding template for item’s display
  • GroupHeaderTemplate : Binding template for list’s header

 

Happy Coding!

image

(originally posted on www.benkotips.com follow me on http://twitter.com/mbenko)

[More]

Working with Xamarin Forms and Navigation

Originally posted on: http://geekswithblogs.net/benko/archive/2014/12/17/working-with-xamarin-forms-and-authentication.aspx

I'm creating a Xamarin.Forms project, using XAML for markup that includes an authentication page when the app starts. I am using a TabbedPage (also tried CarouselPage) as the container of my main UI and plan to have several pages displayed. The first page (myDashboard) checks to see if the user has authenticated and if not I want to display a modal login page. When they return I would like to load data based on their user id.

What's happening is that the Dashboard page loads and is immediately overlaid by the myLogin page, but then all the DisplayAlerts show in succession before I do anything. When I call PopModalAsync() on the login page the OnAppearing method doesn't continue, which indicates to me that the await call had no effect in interrupting the process flow, as if it's already completed the calls after the PushModalAsync() call. (I plan to remove the DisplayAlert calls when it's working as expected.)

My code looks like this...in the App class:


    var mainPage = new TabbedPage() { Children = { new myDashboard() } };
    return mainPage;
    

 

In the myDashboard() class:


    protected async override void OnAppearing()
   {
       base.OnAppearing();
       try
       {

           await DisplayAlert("Alert", "OnAppearing Start", "ok", null);

           if (App.context.IsLoggedIn == false)
           {
               await Navigation.PushModalAsync(new myLogin());

               if (App.context.IsLoggedIn == true)
               {
                   // await LoadData();
                   PageLabel.Text = "Hello " + App.context.UserInfo;
               }
           }

           await DisplayAlert("Alert", "OnAppearing LoggedIn", "ok", null);

           await LoadData();
           await DisplayAlert("Alert", "OnAppearing Complete", "ok", null);
       }
       catch (Exception ex)
       {
           var err = ex.Message;
       }
   }
   

What am I missing?

It appears that because this code is in the OnAppearing() event which is called during a Pop or a Push that the behavior isn’t what is expected. I found an approach in the Xamarin Forums which wires up an event to the login page to send an event and then subscribe to it from the caller (see how-to-navigate-between-contentpages). I removed the code in the OnAppearing event, reserving it for handling core initialization and if the user is logged in I’ll load the data. To implement this approach subscribe to the event in the constructor of your main page…


    public myDashboard()
    {
        InitializeComponent();
        MessagingCenter.Subscribe<myLogin>(this, "LoginComplete",(sender) => LoadData());
    }
    

Then in the login page add code to send the message right after calling PopModalAsync() to close the window.

    
    public async void OnButtonClicked(object sender, EventArgs e)
    {
        var rc = await DisplayAlert("Alert!", "Logged in as " + myPhone.Text, "Ok", "Cancel");
        if (rc == true)
        {
            App.context.IsLoggedIn = true;
            await Navigation.PopModalAsync();
            MessagingCenter.Send<myLogin>(this, "LoginComplete");
        }
    }
    

It works, but is there a better way?

[More]