安裝
1、查看Xaramin.Forms的版本
在vs項目中查看引用的包(Xamarin.Forms)的版本,或者直接進文件夾看 C:\Microsoft\Xamarin\NuGet\xamarin.forms\
可以通過 NuGet 更新到最新的 Xamarin 版本。
開發
XAML
1、xaml中用到的StaticResource的定義
<Setter Property="FontFamily" Value="{StaticResource MontserratRegular}" />
一般在App.xaml中的<Application.Resources><ResourceDictionary>中定義
2、xaml中實例化對象
在xaml上面定義的命名空間別名, xmlns:behaviors="clr-namespace:SkillPool.Core.Behaviors"
使用的時候其實是 實例化的過,例如,類:EventToCommandBehavior,可綁定屬性:EventName、Command
<Entry.Behaviors> <behaviors:EventToCommandBehavior EventName="TextChanged" Command="{Binding ValidateUserNameCommand}" /> </Entry.Behaviors>
3、xaml中定義一些按平台OnPlatform顯示的資源值(Padding、Height)

<OnPlatform x:Key="GridPadding" x:TypeArguments="Thickness"> <On Platform="iOS" Value="20,0,10,15" /> <On Platform="Android, UWP, WinRT, WinPhone" Value="20,15,10,15" /> </OnPlatform> <OnPlatform x:Key="GridHeightRequest" x:TypeArguments="x:Double"> <On Platform="iOS" Value="135" /> <On Platform="Android, UWP, WinRT, WinPhone" Value="150" /> </OnPlatform> <OnPlatform x:Key="PaddingTop" x:TypeArguments="x:Double"> <On Platform="iOS" Value="0" /> <On Platform="Android, UWP, WinRT, WinPhone" Value="15" /> </OnPlatform> <OnPlatform x:Key="FirstRowHeight" x:TypeArguments="GridLength"> <On Platform="iOS" Value="65" /> <On Platform="Android, UWP, WinRT, WinPhone" Value="80" /> </OnPlatform> Padding="{StaticResource GridPadding}" HeightRequest="{StaticResource GridHeightRequest}" <Grid.RowDefinitions> <RowDefinition Height="{StaticResource FirstRowHeight}"/> <RowDefinition Height="30"/> <RowDefinition Height="40"/> </Grid.RowDefinitions>
x:TypeArguments的類型,取決於控件的屬性的類型(查看其定義就知道了),可能位於以下兩個命名空間中:
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
還可以有簡便寫法:
<Style TargetType="Label"> <Setter Property="FontSize" Value="{d:OnPlatform Android=15,Default=12}"/> <Setter Property="BackgroundColor" Value="{OnPlatform Android='Red',Default='Yellow'}"/> </Style>
4、Xaml中引用控件通過Name和x:Reference

<StackLayout.GestureRecognizers> <TapGestureRecognizer Command="{Binding ChildFolderShowOrHideCommand}" NumberOfTapsRequired="1" CommandParameter="{x:Reference childenImg}" /> </StackLayout.GestureRecognizers> <Image x:Name="childenImg" Margin="0" HeightRequest="20" WidthRequest="12" VerticalOptions="Center" HorizontalOptions="StartAndExpand" Source="{Binding ChilrensIsVisible,Mode=OneWay,Converter={StaticResource MailChilrenFolderVisibleConverter}}" IsVisible="{Binding IsHaveChilren,Mode=OneWay}" />
5、布局中Label被擠壓
在一行布局中,第一個Labe(長度很短),第二個Label(長度可能很長),他們樣式不同,第三個是一些圖片。需要不換行顯示,第二個label截斷就好。但是以下xaml在實際中,當第二個label很長時,會造成第一個label顯示不全,給它設置長度都不行,設置HorizontalOptions="FillAndExpand"也不行

<StackLayout Grid.Row="4" Orientation="Horizontal" Margin="0,3,0,0"> <Label Margin="0" Text="發件人" FontSize="15" TextColor="Black" /> <Label Margin="0" Text="huy casfdf@as.com1afdgadhh23456" MaxLines="1" FontSize="15" FontAttributes="Bold" TextColor="#1c86ee" HorizontalOptions="FillAndExpand" LineBreakMode="MiddleTruncation" /> <Label FontSize="15" Text="cadsffs.com" TextColor="Black" IsVisible="False" LineBreakMode="MiddleTruncation" /> <ImageButton Style="{StaticResource ImageButtonSmallStyle}" Source="SenderEncrypt.png"/> <ImageButton Style="{StaticResource ImageButtonSmallStyle}" Source="SenderSignature.png" /> <ImageButton Style="{StaticResource ImageButtonSmallStyle}" Source="lv1.png"/> <ImageButton Style="{StaticResource ImageButtonSmallStyle}" Source="authenticated.png"/> </StackLayout>
不過想到Grid布局,以下可以解決:

<StackLayout Grid.Row="4" Orientation="Horizontal" Margin="0,3,0,0"> <Label Margin="0" Text="發件人" FontSize="15" TextColor="Black" /> <Label Margin="0" Text="huy casfdf@as.com1afdgadhh23456" MaxLines="1" FontSize="15" FontAttributes="Bold" TextColor="#1c86ee" HorizontalOptions="FillAndExpand" LineBreakMode="MiddleTruncation" /> <Label FontSize="15" Text="cadsffs.com" TextColor="Black" IsVisible="False" LineBreakMode="MiddleTruncation" /> <ImageButton Style="{StaticResource ImageButtonSmallStyle}" Source="SenderEncrypt.png"/> <ImageButton Style="{StaticResource ImageButtonSmallStyle}" Source="SenderSignature.png" /> <ImageButton Style="{StaticResource ImageButtonSmallStyle}" Source="lv1.png"/> <ImageButton Style="{StaticResource ImageButtonSmallStyle}" Source="authenticated.png"/> </StackLayout>
6、W/StaticLayout: maxLineHeight should not be -1. maxLines:1 lineCount:1
查看了下xaml中是否有行相關的設置,刪掉試試,什么原因暫時沒搞清
7、頁面的靜態資源無法自動提示
發現xaml中格式字符串引起的,<Label TextColor="Gray" FontSize="15" VerticalOptions="Center" Text="{Binding MailDetailModel.MailDate,StringFormat='{0:yyyy-MM-dd HH:mm:ss}' }"/>
將StringFormat改為Converter去做轉換則可以了。
8、ImageButton的單擊命令去切換圖片顯示的時候,圖像不知怎么的就變小了,改了Aspect屬性也不行
可以改為用Image控件,添加GestureRecognizers去做切換圖片,圖像大小不會變
ViewModel綁定
1、在ViewModel中引用xaml中用x:Name定義的變量
首先獲取頁面:Application.Current.MainPage as MailIndexView;
然后取定義的變量(或者控件),但是控件需要在xaml中命名如下,
x:Name="tabSelectedLayout" x:FieldModifier="Public"
2、控件的Binding 必須是屬性,不能是字段
自定義控件
細微的樣式更改,用效果;復雜的外觀和行為自定義,用自定義呈現器。
1、自定義控件 屬性更改事件的兩種用法
自定義控件包括多個控件時,若子控件Editor的屬性例如Placeholder 需要通過使用自定義控件時 傳過來。則需要將Editor的屬性綁定到自定義控件上,有兩種方式:
- 在屬性的OnPropertyChanged(); 事件中設置
private static void OnPlaceholderChanged(BindableObject bindable, object oldValue, object newValue)
{
if (bindable is AutoCompleteView autocomplete)
{
autocomplete.Placeholder = (string)newValue;
autocomplete.Editor.Placeholder = autocomplete.Placeholder;
}
}
- 在xaml中指定, Placeholder="{Binding Placeholder,Source={x:Reference fm}}",(同時就不用定義OnPropertyChanged參數及事件)

<Frame xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:d="http://xamarin.com/schemas/2014/forms/design" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" xmlns:behavior="clr-namespace:MeSince.Behaviors" xmlns:effect="clr-namespace:MeSince.Effects" x:Class="MeSince.Controls.RoundRadiusEntry" x:Name="fm" HeightRequest="40" Padding="5,0,5,0" CornerRadius="4" HasShadow="False" Margin="0"> <StackLayout Orientation="Horizontal" Padding="0" Margin="0" VerticalOptions="FillAndExpand"> <Entry x:Name="entry" Text="{Binding Text,Source={x:Reference fm}}" Placeholder="{Binding Placeholder,Source={x:Reference fm}}"
調試
1、System.Reflection.TargetInvocationException
Message=Exception has been thrown by the target of an invocation. 調用的目標引發異常。
1.1、注:遇到報錯,首先從VS中看下有沒有具體的原因,而不是一開始就去 Internet找解決方案。
很明顯看出是XAML解析錯誤:EntryStyle資源不存在導致。
1.2、若輸出中沒有明顯的提示,則用斷點調試,定位到哪一塊代碼報錯的,再去分析問題
例如,今天遇到這個問題,將事件改為命令在Viewmodel中執行,始終報上面的錯,定位到問題是如下xaml:

<?xml version="1.0" encoding="utf-8" ?> <TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:d="http://xamarin.com/schemas/2014/forms/design" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="MeSince.Views.Main.BottomTabbedPageView" xmlns:viewModelBase="clr-namespace:MeSince.ViewModels.Base" viewModelBase:ViewModelLocator.AutoWireViewModel="True" xmlns:behaviors="clr-namespace:MeSince.Behaviors" xmlns:converters="clr-namespace:MeSince.Converters" > <TabbedPage.Behaviors> <behaviors:EventToCommandBehavior EventName="CurrentPageChanged" Command="{Binding CurrentPageChangedCommand}" /> </TabbedPage.Behaviors>
看了下EventToCommandBehavior的定義,發現其中base.OnAttachedTo(visualElement);
visualElement的類型定義的是View,,而發現我需要附加行為的是TabbedPage(類型是Page,和View是不同的),於是改為它們的父類VisualElement,問題解決。
即:將
public class EventToCommandBehavior : BindableBehavior<View>
改為
public class EventToCommandBehavior : BindableBehavior<VisualElement>
2、UWP.exe 已附件有調試器,但沒有將該調試器配置為調試此未經處理的異常。若要調試此異常,必須分離當前的調試器
解決方案:嘗試“清理解決方案”,然后在文件資源管理器中打開項目,再刪除 bin 和 obj 文件夾。
https://docs.microsoft.com/zh-cn/previous-versions/hh972445(v=vs.140)?redirectedfrom=MSDN
3、調試CollectionView報錯
報錯:The class, property, or method you are attempting to use ('VerifyCollectionViewFlagEnabled') is part of CollectionView; to use it, you must opt-in by calling Forms.SetFlags("CollectionView_Experimental") before calling Forms.Init().
意思是:您嘗試使用的類,屬性或方法(“ VerifyCollectionViewFlagEnabled”)是CollectionView的一部分; 要使用它,您必須在調用Forms.Init()之前通過調用Forms.SetFlags(“ CollectionView_Experimental”)選擇加入。
在特定平台初始化代碼中加入,
protected override void OnCreate(Bundle savedInstanceState) { global::Xamarin.Forms.Forms.SetFlags("CollectionView_Experimental"); }
4、Specified cast is not valid 指定的轉換無效
在xaml頁面初始化(InitializeComponent ())時報錯,但是沒有具體的信息。
思路:
- 看下ViewModel的綁定屬性是否有誤;
- 控件屬性的類型是否正確,eg: <BoxView CornerRadius="{StaticResource cornerRadius}" />,CornerRadius的類型是CornerRadius而不是Double,CornerRadius寫成了x:Double就會報上面的錯誤。
<OnPlatform x:Key="cornerRadius" x:TypeArguments="CornerRadius"> <On Platform="iOS" Value="3" /> <On Platform="Android, UWP, WinRT, WinPhone" Value="5" /> </OnPlatform>
其它參考:Xamarin深坑集錦