Xamarin.Forms 初探

什么是 Xamarin Forms ?

       Xamarin Forms 是一个高效创建跨平台用户界面的库 。通过Xamarin Forms 可以一次编码生成基于主流移动平台(iOS, Android, Windows Phone)的应用界面。和HTML 5 不同, 它是一套原生的界面解决方案,这意味着通过Xamarin Forms 渲染的界面是与底层API 紧密相连, 那你可以结合诸如iOS 中的Core Motion , PassKit 还有StoreKit 这些API 使用 ,也可以使用诸如NFC / Google Play Service 的Android API ,当然少不了Windows Phone 的Tiles 。

Xamarin Forms 的优势

       通过一次编码,生成多平台界面。假若你做的工作涉及到三个平台,那你会对重重复复的界面逻辑工作厌烦,Xamarin Forms 真的是一个不错的解决方案。

使用 Xamarin Forms 

       你可以通过C#硬编码方式去架构你的界面,还有你可以通过XAML方式去构建。 

Xamarin Forms 能适配的界面

     Pages (页面)  

    

    Layout(布局)  

     

     Controls(控件)

   


好来看看一个简单的例子,由于这篇文章只是初探,我只会把部分精彩的节录下来,大家可以下载代码细看。如果要探究就继续关注我的blog , 接下来会陆续有关于Xamarin Forms 的更深入文章。

      1. 创建Xamarin.Forms 项目      

     


     这里需要说明一点,Xamarin Forms项目有两种模版一种是基于Share Project ,一种是基于PCL ,这里要看各自项目的需要,我默认选取PCL(关于两个模版的使用,我会在之后文章和大家说说)


   2. 创建成功后,会生成包含CnBetaDemo.Shared,CnBetaDemo.iOS, CnBetaDemo.Android 三个项目(如果你用Visual Studio 创建你就会有CnBetaDemo.Windows Phone 的项目) 。 CnBetaDemo.Shared就是我们需要处理的共享逻辑层和Xamarin.Forms。其余两个就是我们所需要对应的平台。 


   3.依据MVVM 方式架构我们的CnBetaDemo.Shared , 这里不得不提到Xamarin 的原理 。Xamarin 是一个基于共享逻辑层的跨平台原生应用方案。

   

    为何用MVVM 在我之前文章有所提及。(博客决定放到csdn,我会迁移后贴上地址)。之前一年的做法是把逻辑共享,现在可以把页面通过Xamarin.Forms进行构造即可,所以CnBetaDemo.Shared就成为了我们跨平台架构项目的核心代码层。


    4.  简单看看ViewModel层 ,这里我以读取CnBeta RSS 为例 ,FeedViewModel 的一些主要代码:

         主要通过async和await 的方式加载数据

		private async Task ExecuteLoadItemsCommand()
		{
			if (isBusy)
				return;

			IsBusy = true;

			try{

				var httpClient = new HttpClient();

				var feed="http://cnbeta.feedsportal.com/c/34306/f/624776/index.rss";


				var responseString = await httpClient.GetStringAsync(feed);

				FeedItems.Clear();

				var items= await ParseFeed(responseString);

				foreach(var item in items)
				{

					//Console.WriteLine(item.Title);
					FeedItems.Add(item);
				}
			}
			catch(Exception ex){

				var page = new ContentPage ();

				var result = page.DisplayAlert ("出错 ", "加载失败.", "确认", null);

			}

			IsBusy = false;

		}

       

                private async Task<List<FeedItem>> ParseFeed(string rss)
		{
			return await Task.Run (() => {
				var xdoc=XDocument.Parse(rss);

				var id=0;

				return ( from item in xdoc.Descendants("item")
					select new FeedItem
					{
						Title = (string)item.Element("title"),
						Description=(string)item.Element("description"),
						PublishDate=(string)item.Element("pubDate"),
						Id= id++
					}).ToList();
			});
		}

       5. 通过Xamarin Forms 构造View 

          这里需要创建一个简单的表单ListView, 和自定义Cell, 当然Xamarin Forms会依旧平台进行相应渲染生成原生的表单支持

	public class FeedView : ContentPage
	{
		private FeedViewModel ViewModel{
			get {  return BindingContext as FeedViewModel;  }
		}

		public FeedView ()
		{

			BindingContext = new FeedViewModel ();

			var stack = new StackLayout {
				Orientation= StackOrientation.Vertical,
				Padding = new Thickness(0,8,0,8)
			};

			var listView = new ListView ();


			listView.ItemsSource = ViewModel.FeedItems;

			var cell = new DataTemplate (typeof(ListTextCell));

			cell.SetBinding (TextCell.TextProperty, "Title");

			cell.SetBinding (TextCell.DetailProperty, "PublishDate");

			listView.ItemTemplate = cell;


			stack.Children.Add (listView);

			Content = stack;
		}

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

			if (ViewModel == null || !ViewModel.CanLoadMore || ViewModel.IsBusy || ViewModel.FeedItems.Count > 0)
				return;

			ViewModel.LoadItemsCommand.Execute (null);
		}
	}

      6. 运行看看

     

     

     

       很Cool吧 !!哈哈!! 欢迎大家下载我的代码看看 点击下载


        对于Xamarin 本人一直很推崇,有了Xamarin Forms更如虎添翼。这里需要排除价格,当然如果是在企业真的可以节省不少。或者你是一个Objective-C 的支持者, 或者是一个Java开发Android的深度码农,但是无可否认Xamarin 可以解决得更多。  


        很开心在CSDN和大家分享,接下来博客在这里安家,也希望大家多和我交流,谢谢!

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Use the solutions provided in this book to handle common challenges in Xamarin.Forms that are encountered on a daily basis. Working examples and techniques are presented that you can modify and drop directly into your own projects. You will be able to deliver working code faster than ever. Examples are made available through GitHub, maximizing the convenience and value this book provides to Xamarin.Forms developers. Solutions in the book are organized broadly into problem domains such as user interface for applications, data and security, connectivity and external services, and more. Within each domain the book presents specific solutions addressing challenges that are commonly faced. Under data and security, for example, you'll find specific solutions around storing login credentials, local data caching, and sending authorization tokens in HTTP requests. Not only do the solutions in the book solve specific problems, they also present best practices that can inform and improve the quality of the code that you write. Xamarin.Forms Solutions is chock full of practical advice and code examples that no Xamarin.Forms programmer will want to be without. The basics of Xamarin.Forms are provided for beginning developers. What You'll Learn Know the in-depth basics of Xamarin.Forms and the inner workings Create custom renderers and dependency services Manage the appearance of user interfaces through styling and theming, layout options, rotation, and animation Build sophisticated user interfaces using a variety of controls that allow for PDF viewing, barcode interpretation, searching and finding, and other controls Secure your applications, and communicate securely with services via HTTP requests Sign and deploy your apps and optimize the binary file size Who This Book Is For Those building mobile applications on the Xamarin platform for iOS and Android. By mixing together the solutions and a thorough explanation of the basics of Xamarin.Forms, the book spans the needs of beginning through intermediate Xamarin.Forms developers. Even experts will find a few gems to improve the quality and speed of their application development work.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值