c# - Xamarin Forms BindableProperty 在构造函数之前更改

标签 c# xaml binding xamarin.forms

我正在通过 App.xaml 中的 XAML 添加资源。该资源是一种隐式样式,将分配给 CustomControl。 CustomControl 包含一个标签。

为了设置此标签的 TextColor,我在 CustomControl 上创建一个可绑定(bind)属性,并使用隐式样式分配一个值。使用 BindableProperty 的 PropertyChanged 方法,我在 CustomControl 中设置了标签的 TextColor。

<Style TargetType="CustomControl" >
     <Setter Property="InnerLabelTextColor" Value="Green" />
</Style>

-

private static void InnerLabelTextColorChanged(BindableObject bindableObject, object oldValue, object newValue)
{
    ((CustomControl)bindableObject).InnerLabel.TextColor = (Color)newValue;
}

这曾经在 XF 2.3.2.127 中工作,但当我更新到 XF 2.3.4.270 时,我开始在 CustomControl - BindableProperty - 中收到 NullReferenceException - InnerLabelTextColorChanged 方法。

PropertyChanged 方法在执行构造函数之前被调用。当执行 PropertyChanged 方法时,我的 InnerLabel 为 null,这会导致 NullReferenceException。

我想知道此行为是请求的 XF 行为还是一个错误?

如果这是所请求的行为,任何人都可以提供处理这种情况的正确方法吗?

谢谢!

编辑 - 自定义控件代码示例

public sealed class CustomControl : ContentView
{
    public static readonly BindableProperty InnerLabelTextColorProperty =
        BindableProperty.Create("InnerLabelTextColor", typeof(Color), typeof(CustomControl), Color.Black,
            BindingMode.OneWay, null, CustomControl.InnerLabelTextColorChanged, null, null, null);


    public CustomControl()
    {
        this.InnerLabel = new Label();

        this.Content = this.InnerLabel;
    }


    public Label InnerLabel { get; set; }


    public Color InnerLabelTextColor
    {
        get
        {
            return (Color)this.GetValue(CustomControl.InnerLabelTextColorProperty);
        }
        set
        {
            this.SetValue(CustomControl.InnerLabelTextColorProperty, value);
        }
    }


    private static void InnerLabelTextColorChanged(BindableObject bindableObject, object oldValue, object newValue)
    {
        ((CustomControl)bindableObject).InnerLabel.TextColor = (Color)newValue;
    }
}

最佳答案

我曾参与过similar issue不久前,唯一的区别是在基于 XAML 的控件中遇到了这种情况。

我认为这个问题的根本原因是(当我们使用这样的全局隐式样式时)基本构造函数尝试设置该可绑定(bind)属性,并且由于派生构造函数仍在等待轮到它,所以我们遇到了 null引用。

解决此问题的最简单方法是使用 Binding 设置内部子控件 ( reference ) 的属性:

public CustomControl()
{
    this.InnerLabel = new Label();

    // add inner binding
    this.InnerLabel.SetBinding(Label.TextColorProperty, 
         new Binding(nameof(InnerLabelTextColor), 
                     mode: BindingMode.OneWay, 
                     source: this));  

    this.Content = this.InnerLabel;
}

关于c# - Xamarin Forms BindableProperty 在构造函数之前更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46523431/

相关文章:

c# - 如何获取表的PRIMARY KEY列名

C# > XML-RPC.NET > Python MailMan

c# - 动态调整 UserControl 大小的 WPF XAML 数据绑定(bind)

WPF触发器属性

c# - TextBox 中的居中占位符文本

c# - 在 WPF 中绑定(bind)两个依赖属性

javascript - Backbone 和 bindAll : "func is undefined"

c# - 可能吗? c# 中的 GUI,C++ 中的应用程序

c# - 在 Windows C# 之间传递对象

r - t 作为 R 中全局变量的名称 : impossible?