我试图弄清楚如何在Xamarin.Forms中将.axml布局文件用于自定义控件。谁能提供在自定义渲染器中使用.axml文件的示例吗?例如,我要创建一个自定义的Entry控件(EnhancedEntry)。我希望它具有可配置的背景和边框颜色以及可配置的边框宽度。

我已经创建了背景形状,

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); }
        }
    }

最佳答案

您可以在OnElementChanged()中配置您正在谈论的属性,将渲染的Entry称为Control。它不在axml或xml中,但仍然可能。

显然,在VS的解决方案资源管理器中,您可以单击“显示所有文件”,它将显示Android.Resource.Layout文件夹以添加自定义布局文件。我说这显然是因为这对我不起作用,但是如果您仍然希望在xml中使用它,则值得尝试。

完成此操作后,您应该能够在OnElementChanged()方法中引用自定义视图的布局文件,但是我发现在一个地方轻松完成所有操作!

10-07 19:36
查看更多