Xamarin.Forms 可绑定属性
Posted
技术标签:
【中文标题】Xamarin.Forms 可绑定属性【英文标题】:Xamarin.Forms Bindable Properties 【发布时间】:2021-03-11 12:06:59 【问题描述】:这听起来像是一个愚蠢的问题,但为什么可绑定属性是静态的?
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 个地图,如果我在其中一个上设置此值,那么这两个地图上的值将相同?
【问题讨论】:
【参考方案1】:每个可绑定属性都有一个对应的BindableProperty
类型的public static readonly
字段,该字段在同一类上公开,是可绑定属性的标识符。
您可以查看提供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 文档以了解更多关于可转换属性中的静态的信息。 https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/bindable-properties
【讨论】:
以上是关于Xamarin.Forms 可绑定属性的主要内容,如果未能解决你的问题,请参考以下文章