【发布时间】:2015-12-12 22:00:24
【问题描述】:
我在将 Xamarin 表单中的自定义视图中的数据绑定到包含页面的视图模型时遇到问题。
我的自定义视图很简单,一对标签代表一个键值对:
<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}" />
问题是 Key 字符串按预期显示,但 value 字符串没有。 我尝试在 document_number 属性上强制执行 PropertyChanged 事件,但这没有帮助。 我还尝试在自定义视图的键/值属性的设置器中显式设置标签上的文本属性:
public string Key
{
get {return (string)GetValue(KeyProperty);}
set {
SetValue(KeyProperty, value);
KeyLabel.Text = value;
}
}
这同样没有帮助,setter 代码似乎永远不会被执行(我在它上面放置了一个断点,它没有被命中)
如果我添加一个开箱即用的控件,例如直接绑定到页面中的属性的标签,则显示正确:
<Label Text="{Binding document_number}"/>
<views:KeyValueView Key="Order Number" Value="{Binding document_number}" />
谁能解释为什么会发生(或者说没有发生)?
【问题讨论】:
标签: c# xaml xamarin xamarin.forms