我复制/编写了一个继承自Frame的类
public class Circle : Frame
{
//private double _radius;
public static readonly BindableProperty RadiusProperty = BindableProperty.Create(nameof(Radius), typeof(double), typeof(Circle), 126.0, BindingMode.TwoWay);
public double Radius
{
get => (double)GetValue(RadiusProperty); //_radius;
set
{
SetValue(RadiusProperty, value);
OnPropertyChanged();
AdjustSize();
}
}
private void AdjustSize()
{
HeightRequest = Radius;
WidthRequest = Radius;
Margin = new Thickness(0,0,0,0);
Padding = new Thickness(0, 0, 0, 0);
CornerRadius = (float) (Radius / 2);
}
public Circle()
{
HorizontalOptions = LayoutOptions.Center;
}
}
消费页面定义了这些 BinadableProperties
public static readonly BindableProperty InnerColorProperty = BindableProperty.Create("InnerColor", typeof(Color), typeof(CircleProgressView), defaultValue: Color.FromHex("#34495E"), BindingMode.TwoWay);
public Color InnerColor
{
get => (Color)GetValue(InnerColorProperty);
set => SetValue(InnerColorProperty, value);
}
public static readonly BindableProperty InnerRadiusProperty = BindableProperty.Create("InnerRadius", typeof(double), typeof(CircleProgressView), 126.0, BindingMode.TwoWay);
public double InnerRadius
{
get => (double)GetValue(InnerRadiusProperty);
set => SetValue(InnerRadiusProperty, value);
}
并像这样使用Circle
<components:Circle Grid.Row="0" BackgroundColor="{Binding InnerColor}" Radius="{Binding InnerRadius}" >
唉,可绑定的设置器,因此 AdjustSize(),从未被调用,也没有使用默认值。我最终得到了一个矩形,而不是一个圆圈。BackgroundColor是Frame的一个属性,可以绑定并正常工作。
如果我删除 BindableProperty 并留下常规的 INotify 属性
public class Circle : Frame
{
private double _radius;
public double Radius
{
get => _radius;
set
{
_radius = value;
OnPropertyChanged();
AdjustSize();
}
}
private void AdjustSize()
{
HeightRequest = Radius;
WidthRequest = Radius;
Margin = new Thickness(0,0,0,0);
Padding = new Thickness(0, 0, 0, 0);
CornerRadius = (float) (Radius / 2);
}
public Circle()
{
HorizontalOptions = LayoutOptions.Center;
}
}
如果我保留InnerRadius绑定,编译器会抱怨
严重性代码描述项目文件行抑制状态错误位置 17:92。未找到“半径”的属性、可绑定属性或事件,或者值和属性之间的类型不匹配。...\组件\CircleProgressView.xaml 17
我可以用硬编码值替换Radius绑定,它运行良好,出现一个圆圈。
<components:Circle Grid.Row="0" BackgroundColor="{Binding InnerColor}" Radius="126" >
常规 C# 类中的 BindableProperty 有什么问题?