0

这听起来像是一个愚蠢的问题,但为什么可绑定属性是静态的?

public static readonly BindableProperty MapSpanProperty = BindableProperty.Create
            (
                propertyName: "MapSpan",
                returnType: typeof(MapSpan),
                declaringType: typeof(BindableMap),
                defaultValue: null,
                defaultBindingMode: BindingMode.TwoWay,
                propertyChanged: MapSpanPropertyChanged
            );

        public MapSpan MapSpan
        {
            get
            {
                return (MapSpan)GetValue(MapSpanProperty);
            }
            set
            {
                SetValue(MapSpanProperty, value);
            }
        }

我有这段代码,如果我将可绑定属性设为静态,它就可以正常工作,否则它就不起作用。如果我将此可绑定属性设为静态,这意味着,假设我同时打开了 2 个地图,如果我在其中一个上设置此值,那么这两个地图上的值是否相同?

4

1 回答 1

0

每个可绑定属性都有一个对应public static readonly的类型字段,该字段BindableProperty在同一类上公开,并且是可绑定属性的标识符。

您可以检查提供 binable 属性的控件的源代码。

例如,我使用内容视图。代码来自下面的链接。Xamarin 表单从可绑定属性更新视图模型字段

public partial class MyCustomControl : ContentView
{
    private string _text;
    public string Text
    {
        get { return _text; }
        set
        {
            _text = value;
            OnPropertyChanged();
        }
    }
    public static readonly BindableProperty TextProperty = BindableProperty.Create(
             nameof(Text),
             typeof(string),
             typeof(MyCustomControl),
             string.Empty,
             propertyChanged: (bindable, oldValue, newValue) =>
             {
                 var control = bindable as MyCustomControl;
                 //var changingFrom = oldValue as string;
                 //var changingTo = newValue as string;
                 control.Title.Text = newValue.ToString();
             });
    
    public MyCustomControl()
    {
        InitializeComponent();
    }

提供ContentView公共静态只读 BindableProperty。

  //
// Summary:
//     An element that contains a single child element.
//
// Remarks:
//     The following example shows how to construct a new ContentView with a Label inside.
[ContentProperty("Content")]
public class ContentView : TemplatedView
{
    //
    // Summary:
    //     Backing store for the Xamarin.Forms.ContentView.Content property..
    //
    // Remarks:
    //     To be added.
    public static readonly BindableProperty ContentProperty;

    public ContentView();

    //
    // Summary:
    //     Gets or sets the content of the ContentView.
    public View Content { get; set; }

    //
    // Summary:
    //     Method that is called when the binding context changes.
    //
    // Remarks:
    //     To be added.
    protected override void OnBindingContextChanged();
}

您可以查看 MS 文档以了解更多关于可二进制属性中的静态的信息。https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/bindable-properties

于 2021-03-12T07:59:22.327 回答