【问题标题】:How to do a binding on a property using a custom control?如何使用自定义控件对属性进行绑定?
【发布时间】:2019-07-12 14:59:57
【问题描述】:

我创建了一个自定义条目,您可以在此处看到:

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

但我的控件的边框颜色没有改变。

我不知道我做错了什么..

【问题讨论】:

  • 两件事。 1. 确保 ColorErorr 正在实施INotifyPropertyChanged。 2. 在您的渲染器中,您需要覆盖OnElementPropertyChanged。这是每当 BordercColor 改变时都会触发的方法。
  • Thnak 的!效果很好!
  • 太棒了。如果你有时间,你可以回答你自己的问题。这将对可能遇到相同问题的其他用户有所帮助。

标签: xamarin binding custom-controls


【解决方案1】:

我的问题有答案了:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-11
    • 2011-05-11
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    相关资源
    最近更新 更多