我在Xamarin Forms中的自定义视图中,无法将数据绑定到包含页面的视图模型上,希望能得到帮助。
我的自定义视图非常简单,只是一对表示键值对的标签:
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="KeyValueView">
<Grid VerticalOptions="Start">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label x:Name="KeyLabel" Text="{Binding Key}" Grid.Column="0" HorizontalOptions="Start" />
<Label x:Name="ValueLabel" Text="{Binding Value}" Grid.Column="1" HorizontalOptions="EndAndExpand" />
</Grid>
</ContentView>
使用以下代码:
public partial class KeyValueView : ContentView
{
public KeyValueView()
{
InitializeComponent();
this.VerticalOptions = LayoutOptions.Start;
this.BindingContext = this;
}
public static readonly BindableProperty ValueProperty =
BindableProperty.Create<KeyValueView, string>(w => w.Value, default(string));
public string Value
{
get {return (string)GetValue(ValueProperty);}
set {SetValue(ValueProperty, value);}
}
public static readonly BindableProperty KeyProperty =
BindableProperty.Create<KeyValueView, string>(w => w.Key, default(string));
public string Key
{
get {return (string)GetValue(KeyProperty);}
set {SetValue(KeyProperty, value);}
}
}
以下是在页面中使用的方式:
<views:KeyValueView Key="Order Number" Value="{Binding document_number}" />
问题在于键字符串显示正常,但是值字符串没有显示。
我尝试强制触发document_number属性的PropertyChanged事件,但是这并没有帮助。
我还尝试在自定义视图的Key/Value属性的setter期间显式设置Labels的Text属性:
public string Key
{
get {return (string)GetValue(KeyProperty);}
set {
SetValue(KeyProperty, value);
KeyLabel.Text = value;
}
}
再试了一遍,这并没有帮助,设置器代码似乎从未被执行过(我在上面放了一个断点但它并未被触发)
如果我添加一个开箱即用的控件,例如一个直接绑定到页面属性的标签,它将正确显示:
<Label Text="{Binding document_number}"/>
<views:KeyValueView Key="Order Number" Value="{Binding document_number}" />
有人能解释一下为什么会发生这种情况吗(或者更确切地说,为什么没有发生)?