【问题标题】:How to bind bindable object to the xml file in xamarin forms如何将可绑定对象绑定到 xamarin 表单中的 xml 文件
【发布时间】:2019-03-28 05:29:16
【问题描述】:

我使用自定义渲染器为 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# xml xamarin xamarin.forms binding


    【解决方案1】:

    你可以通过设置drawable的stroke color来做到这一点。

    代码:

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

    用我的代码更改自定义堆栈视图渲染器中的 OnElementChanged 方法,并将 BorderColor 属性值替换为真实数据。这就是你所要做的。

    编码愉快!

    【讨论】:

    • 我已经尝试过你的代码,但它会返回以下异常,Unhandled Exception: Java.Lang.IllegalArgumentException: Unknown color
    • @Yogeshwaran,我已经更新了我的代码。请看一看。
    猜你喜欢
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 2014-04-15
    • 2016-01-03
    • 1970-01-01
    • 2018-11-15
    相关资源
    最近更新 更多