如何使用自定义控件对属性执行绑定



我创建一个自定义条目,如下所示:

public class ExtendedEntry : Entry
{
    public static readonly BindableProperty BorderColorProperty =
        BindableProperty.Create(nameof(BorderColor), typeof(Color), typeof(ExtendedEntry), Color.Gray);
    public Color BorderColor
    {
        get { return (Color) GetValue(BorderColorProperty); }
        set { SetValue(BorderColorProperty, value); }
    }
}

我创建了一个自定义渲染器,如下所示:

[assembly: ExportRenderer(typeof(ExtendedEntry), typeof(MyEntryRenderer))]
namespace LogiStock.UWP.CustomRenderers
{
    public class MyEntryRenderer : EntryRenderer
    {
        ExtendedEntry entry;
        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);
            entry = (ExtendedEntry)Element;
            if (Control != null)
            {
                var converter = new ColorConverter();
                Control.BorderBrush = (SolidColorBrush)converter.Convert(entry.BorderColor, null, null, null);
            }
        }
    }
}

我在 xaml 中使用了我的自定义控件,如下所示:

<controls:ExtendedEntry BorderColor="{Binding ColorError, Mode=TwoWay}"/>

最后,我在视图模型中测试我的条目是否为空,如果为空,我想要颜色:

if (string.IsNullOrWhiteSpace(Libelle))
{
    ColorError = Color.Red;
}

但是我控制的边界颜色没有改变。

我不知道我做错了什么。

我的问题的答案是:

我在渲染器中覆盖OnElementPropertyChanged,并在声明属性的类中实现接口ÌNotifyPropertyChanged ColorError

最新更新