2016-10-27 157 views
0

我想弄清楚如何在Xamarin.Forms中使用.axml佈局文件的自定義控件。任何人都可以提供在自定義渲染器中使用.axml文件的示例嗎?例如,我想創建一個自定義的Entry控件(EnhancedEntry)。我希望它具有可配置的背景和邊框顏色以及可配置的邊框寬度。Xamarin.Forms從.axml佈局Android控制自定義渲染器

我創建背景的形狀,

drawable/enchancedEntryBackground.xml: 

<?xml version="1.0" encoding="UTF-8"?> 
    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> 
     <corners android:bottomLeftRadius="3dp" android:bottomRightRadius="3dp" android:topLeftRadius="3dp" android:topRightRadius="3dp" /> 
     <stroke android:width="0.5dp" android:color="@android:color/holo_blue_dark" /> 
     <solid android:color="@android:color/white" /> 
    </shape> 

我有一個由此.axml文件中定義的佈局,

layout/EnhancedEntry.axml 

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:minWidth="25px" 
    android:minHeight="25px"> 
    <EditText 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/enhancedEntry" 
     android:background="@drawable/enhancedentrybackground" /> 
</LinearLayout> 

給定自定義渲染骨架和類屬性,以便支持增強,是否可以使用xml和axml規範來創建新外觀?

[assembly: ExportRenderer(typeof(EnhancedEntry), typeof(EnhancedEntryRenderer))] 
namespace eSiteMobile.Droid.CustomRenderers 
{ 

    public class EnhancedEntryRenderer : EntryRenderer 
    { 
     protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) 
     { 
      base.OnElementChanged(e);    
     } 

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

public class EnhancedEntry : Entry 
    { 
     public static BindableProperty BorderColorProperty = BindableProperty.Create(nameof(BorderColor), typeof(Color), 
      typeof(EnhancedEntry), default(Color), defaultBindingMode: BindingMode.OneWay); 

     public static BindableProperty BorderWidthProperty = BindableProperty.Create(nameof(BorderWidth), typeof(int), 
      typeof(EnhancedEntry), default(int), defaultBindingMode: BindingMode.OneWay); 

     public Color BorderColor 
     { 
      get { return (Color) GetValue(BorderColorProperty); } 
      set { SetValue(BorderColorProperty, value); } 
     } 

     public int BorderWidth 
     { 
      get { return (int) GetValue(BorderWidthProperty); } 
      set { SetValue(BorderWidthProperty, value); } 
     } 
    } 

回答

1

可以在OnElementChanged()配置您所談論的屬性指的是呈現EntryControl。它不在axml或xml中,但仍然可能。

顯然,在VS的解決方案資源管理器中,您可以單擊「顯示所有文件」,它將顯示Android.Resource.Layout文件夾以添加自定義佈局文件。我說明顯是因爲這對我不起作用,但如果你仍然想在xml中使用它,那麼值得一試。

完成之後,您應該能夠參照您在OnElementChanged()方法中自定義視圖的佈局文件,但是我發現在一個位置更容易完成所有操作!

相關問題