问题描述
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 个地图,如果我将其设置在其中一个地图上,则该值在两个地图上将相同?
解决方法
每个可绑定属性都有一个对应的 public static readonly
类型的 BindableProperty
字段,该字段暴露在同一类中,并且是可绑定属性的标识符。
您可以查看提供 binable 属性的控件的源代码。
例如,我使用内容视图。代码来自下面的链接。 Xamarin forms update viewmodel field from a bindable property
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 文档,了解更多有关 binable 属性中的静态信息。 https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/bindable-properties