我正在尝试创建一个简单的Xamarin.Forms自定义控件,并遇到了绑定问题。
这是我的初始自定义控件:
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="CubisMobile.Controls.TestControl"
x:Name="TestControlView">
<Label Text="{Binding TestText}" />
public partial class TestControl : ContentView
{
public static readonly BindableProperty TestTextProperty = BindableProperty.Create(nameof(TestText), typeof(string), typeof(TestControl));
public string TestText
{
get { return (string)GetValue(TestTextProperty); }
set { SetValue(TestTextProperty, value); }
}
public TestControl()
{
InitializeComponent();
BindingContext = this;
}
}
我正在尝试这样使用它:
...
<StackLayout>
<controls:TestControl TestText="{Binding Title}" />
<Label Text="{Binding Title}" />
</StackLayout>
...
我添加了第二个标签来测试Title属性是否正常工作,结果它是正常的。
但是文本不会显示在自定义控件上。当我设置一个固定值时,例如 TestText="Testing"
它就按预期运行。我在 StackOverflow 上找到了 这个答案,尝试了下面的方法,但也没有起作用(自定义控件XAML):
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="CubisMobile.Controls.TestControl"
x:Name="TestControlView">
<Label Text="{Binding Source={x:Reference TestControlView}, Path=TestText}" />
我真的不明白为什么这个绑定没起作用。