首页 > 解决方案 > 如何将可绑定对象绑定到 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>

标签: c#xmlxamarinxamarin.formsbinding

解决方案


您可以通过设置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方法,并将您的属性值替换为真实数据。这就是你所要做的。

快乐编码!


推荐阅读