我想声明一个 BindableProperty
,它充当 Xamarin.Forms 中另一个 BindableProperty
的便利属性。设置其中一个将更新另一个。我不会给出完整的上下文和实际类型,但一个非常简单且易于理解的场景如下:
我有一个定义 Number 和 Numberp1 属性的 View 。 Number 是可绑定(bind)的,而 Numberp1 属性在这里充当方便属性。
//Definition
public class MyView : ContentView
{
public static BindableProperty NumberProperty = BindableProperty.Create(nameof(Number), typeof(int), typeof(MyView));
public int Number { get => (int)GetValue(NumberProperty); set => SetValue(NumberProperty, value); }
public int Numberp1 { get => Number + 1; set => Number = value - 1; }
}
//Usage
<local:MyView Number="{Binding Number}"/>
一切进展顺利,直到客户发现 Numberp1 不可绑定(bind)并希望我将其设置为可绑定(bind)。
<local:MyView Numberp1="{Binding Numberp1}"/>
//error : No property, bindable property, or event found for 'Numberp1', or mismatching type between value and property.
我如何使这两个属性都可绑定(bind)但使它们相互更新?我尝试使用转换器进行调查,但它们似乎只能在绑定(bind)中使用,而不能在 BindableProperty
定义中使用。
最佳答案
Things go well until a customer discovers that Numberp1 isn't bindable and would like me to make it bindable.
请为 Numberp1 创建另一个 BindableProperty,BindableProperty“Numberp1Property”的占位符应始终与不带“Property”的名称匹配。
public static BindableProperty NumberProperty = BindableProperty.Create(nameof(Number), typeof(int), typeof(MyView11), null, propertyChanged: OnNumberChanged);
private static void OnNumberChanged(BindableObject bindable, object oldValue, object newValue)
{
var num = (MyView11)bindable;
num.Number = (int)newValue;
}
public static BindableProperty NumberpProperty = BindableProperty.Create(nameof(Numberp), typeof(int), typeof(MyView11), null, propertyChanged: OnNumber1Changed);
private static void OnNumber1Changed(BindableObject bindable, object oldValue, object newValue)
{
var num = (MyView11)bindable;
num.Numberp = (int)newValue;
}
public int Number
{
get => (int)GetValue(NumberProperty);
set => SetValue(NumberProperty, value);
}
public int Numberp
{
get => Number + 1;
set => Number = value - 1;
}
为 BindableProperty 添加 propertyChanged 事件。
关于c# - 如何在 Xamarin.Forms 中定义两个可相互更新的可绑定(bind)属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55810305/