在Xamarin.Forms中绑定自定义视图
我在将Xamarin表单中的自定义视图中的数据绑定到包含页面的视图模型时遇到问题。
我的自定义视图非常简单,一对代表键值对的标签:
后面的代码:
public partial class KeyValueView : ContentView { public KeyValueView() { InitializeComponent(); this.VerticalOptions = LayoutOptions.Start; this.BindingContext = this; } public static readonly BindableProperty ValueProperty = BindableProperty.Create(w => w.Value, default(string)); public string Value { get {return (string)GetValue(ValueProperty);} set {SetValue(ValueProperty, value);} } public static readonly BindableProperty KeyProperty = BindableProperty.Create(w => w.Key, default(string)); public string Key { get {return (string)GetValue(KeyProperty);} set {SetValue(KeyProperty, value);} } }
这在页面中消耗如下:
问题是Key字符串按预期显示,但值字符串不是。 我试过在document_number属性上强制一个PropertyChanged事件,这没有帮助。 我还尝试在自定义视图的键/值属性的设置器中显式设置标签上的Text属性:
public string Key { get {return (string)GetValue(KeyProperty);} set { SetValue(KeyProperty, value); KeyLabel.Text = value; } }
再次这没有帮助,setter代码似乎永远不会被执行(我在它上面放置了一个断点并且没有被击中)
如果我添加一个开箱即用的控件,例如直接绑定到页面中属性的Label,则会正确显示:
谁能解释为什么会发生这种情况(或者更确切地说没有发生)?
不要在自定义控件内部分配绑定。 用这个:
public partial class KeyValueView : ContentView { public KeyValueView() { InitializeComponent(); this.VerticalOptions = LayoutOptions.Start; } public static readonly BindableProperty ValueProperty = BindableProperty.Create(w => w.Value, default(string)); public string Value { get {return (string)GetValue(ValueProperty);} set {SetValue(ValueProperty, value);} } public static readonly BindableProperty KeyProperty = BindableProperty.Create(w => w.Key, default(string)); public string Key { get {return (string)GetValue(KeyProperty);} set {SetValue(KeyProperty, value);} } protected override void OnPropertyChanged(string propertyName) { base.OnPropertyChanged(propertyName); if (propertyName == ValueProperty.PropertyName) { ValueLabel.Text = Value; } if (propertyName == KeyProperty.PropertyName) { KeyLabel.Text = Key; } } }
将属性(例如,值)视为对BindableProperty(ValueProperty)的引用。 如果你在Value setter BindableProperty中做了什么就不会被通知它,如果你用BindableProperty(分配/更改ValueProperty)做某事就相反 – 属性值setter将不会被调用。
如果要处理PropertyChanged,则可以覆盖(OnPropertyChanged)或Actions(作为创建BindableProperty时的附加参数)。
我能够通过这样做来实现这一目标
public KeyValueView() { InitializeComponent(); this.VerticalOptions = LayoutOptions.Start; this.Content.BindingContext = this; }
然后在xaml.cs中为您正在使用自定义视图的视图执行此操作:
public ParentView() { InitializeComponent(); BindingContext = this; }
对于一个给我带来问题的Entry字段,我必须确保defaultBindingMode参数设置为TwoWay。