【发布时间】:2018-03-13 09:38:26
【问题描述】:
我在我的 App.xaml 中通过 XAML 添加资源。此资源是一种隐式样式,将分配给 CustomControl。 CustomControl 包含一个标签。
为了设置此标签的 TextColor,我在 CustomControl 上创建了一个可绑定属性,并使用隐式样式分配了一个值。使用 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;
}
}
【问题讨论】:
-
放你的自定义控制代码
-
@ZiyadGodil。我在问题中添加了一个代码示例。
标签: c# xaml binding xamarin.forms