【发布时间】:2020-04-03 18:04:21
【问题描述】:
我复制/编写了一个继承自 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}" >
唉,可绑定的 setter 以及因此的 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。未找到“半径”的属性、可绑定属性或事件,或者值和属性之间的类型不匹配。 ...\Components\CircleProgressView.xaml 17
我可以用硬编码值替换 Radius 绑定,它运行良好,出现一个圆圈。
<components:Circle Grid.Row="0" BackgroundColor="{Binding InnerColor}" Radius="126" >
常规 C# 类中的 BindableProperty 有什么问题?
【问题讨论】:
-
处理您要使用的属性更改property-changed callbacks
-
还建议您避免使用双向绑定模式(您不希望半径成为输入)
标签: xamarin.forms bindableproperty