c# - 如何将可绑定对象绑定到 xamarin 表单中的 xml 文件
问题描述
我使用自定义渲染器为 android 创建了自定义边框堆栈布局。StackLayout 边框是使用 xml 文件创建的。边框颜色在该 xml 文件中定义。但我想在运行时使用可绑定对象属性动态更改边框颜色。我已经用 ios 做到了这一点。但我不知道如何将可绑定对象绑定到 xml 文件。下面提到了我的 customBorderStacklayout 示例代码,请分享您的宝贵建议。
CustomStackBorder.cs
public class CustomStackBorder : StackLayout
{
public Color BorderColor
{
get { return (Color)GetValue(BorderColorProperty); }
set { SetValue(BorderColorProperty, value); }
}
public static readonly BindableProperty BorderColorProperty =
BindableProperty.Create("BorderColor", typeof(Color), typeof(CustomStackBorder), Color.Gray, BindingMode.TwoWay);
public CustomStackBorder()
{
}
}
CustomStackLayoutRenderer.cs (Android)
public class CustomStackLayoutRenderer : VisualElementRenderer<StackLayout>
{
public CustomStackLayoutRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<StackLayout> e)
{
base.OnElementChanged(e);
Background = ContextCompat.GetDrawable(this.Context, Resource.Drawable.StackLayoutBorder);
}
}
StackLayoutBorder.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<stroke android:width="0.1dp" android:color="#ff555555"></stroke>
<corners android:topLeftRadius="2dp"
android:topRightRadius="2dp"
android:bottomLeftRadius="2dp"
android:bottomRightRadius="2dp" />
<solid android:color="#ffffff"/>
</shape>
解决方案
您可以通过设置drawable 的笔触颜色来做到这一点。
代码:
protected override void OnElementChanged(ElementChangedEventArgs<StackLayout> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
if (e.NewElement as CustomStackBorder != null)
{
Background = ContextCompat.GetDrawable(this.Context, Resource.Drawable.StackLayoutBorder);
GradientDrawable bgShape = (GradientDrawable)this.Background;
bgShape.SetStroke(1, (e.NewElement as CustomStackBorder).BorderColor.ToAndroid());
}
}
}
使用我的代码更改自定义堆栈视图渲染器中的OnElementChangedBorderColor
方法,并将您的属性值替换为真实数据。这就是你所要做的。
快乐编码!
推荐阅读
- azure - azure 上生产的 Blazor 服务器:工作一段时间然后突然在所有 css/脚本文件上出现 404?
- flutter - 如何清除flutter web中的堆内存?
- javascript - 当命名函数位于匿名函数中时,为什么“this”关键字不起作用?
- javascript - 如何在javascript中将第一个输出转换为第二个输出?
- python - 使用 groupby 时 pandas 数据框的访问键
- amcharts - 检索 amchart4 treeMap 的叶子(框)的名称
- python - Apache 气流可以在 Windows 上使用吗?应该提前做什么?
- python - 如何从文本文件发送 ket
- c# - 如何检查用户输入是否为数字,以及它是否与同一个 while 循环中的另一个变量相同?
- java - SnakeYaml 在 yaml 中的当前日期时间