c# - 如何在 Xamarin.Forms 中定义两个可相互更新的可绑定(bind)属性?

标签 c# xamarin.forms

我想声明一个 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/

相关文章:

c# - 如何访问同一命名空间中的静态类但另一个程序集?

c# - SoapCoreOptions.Binding 现已过时

c# - PrivateObject 类的 GetField() 方法可以访问 C# 4.0 中的私有(private) const 字符串吗?

c# - SQL Server 和 C# 之间的性能问题

c# - Xamarin.iOS 使用 MSALauthentication_ui_failed : The browser based authentication dialog failed to complete

c# - 使用野田时间记录和计算丰富的流逝时间

c# - Xamarin.Forms - HttpClient SendAsync 中未处理的异常

xamarin - 您可以将 Xamarin.Forms 4.0 与 Shell 和 Prism 框架一起使用吗

sqlite - 创建数据库时该列已存在

c# - 每隔几秒自动刷新或更新内容页面