我正在尝试弄清楚如何在 Xamarin.Forms 中为自定义控件使用 .axml 布局文件。谁能提供在自定义渲染器中使用 .axml 文件的示例?例如,我想创建一个自定义条目控件 (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()
方法中自定义 View 的布局文件,但我发现在一个地方完成所有操作更容易!
关于c# - 来自 .axml 布局的 Android 控件的 Xamarin.Forms 自定义渲染器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40292767/