我创建了一个ContentView
带有单个标签的标签(我计划稍后添加更多)。
PageHeadingView.xaml
<ContentView.Content>
<StackLayout Orientation="Vertical" BackgroundColor="Red">
<Label x:Name="HeadingLabel" Text="{Binding HeadingText}" />
</StackLayout>
</ContentView.Content>
我在后面的代码中定义了一个BindableProperty
。我还将BindingContext
我的视图设置为它自己。
PageHeadingView.xaml.cs
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class PageHeadingView : ContentView
{
public PageHeadingView()
{
InitializeComponent();
this.BindingContext = this;
}
public static readonly BindableProperty HeadingTextProperty = BindableProperty.Create(nameof(HeadingText), typeof(string), typeof(PageHeadingView), default(string));
public string HeadingText { get => (string)GetValue( HeadingTextProperty); set => SetValue(HeadingTextProperty, value); }
}
然后我将视图添加到我的 ContentPage。我还在 StackLayout 中添加了一个测试标签,以确保我的绑定正常工作。
主页.xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:views="clr-namespace:MyProject.Views"
x:Class="MyProject.HomePage">
<ContentPage.Content>
<StackLayout Orientation="Vertical">
<views:PageHeadingView HeadingText="{Binding Name}" />
<Label Text="{Binding Name}" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
并设置我BindingContext
的代码。
主页.xaml.cs
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class HomePage : ContentPage
{
public HomePage()
{
InitializeComponent();
//ViewModel contains a string property named: Name;
this.BindingContext = new ViewModel();
}
}
当我运行我的代码时,我的 PageHeadingView 不显示任何文本。我可以看到红色的背景颜色,所以我知道控件已正确添加到页面中。我在 StackLayout 中放置的测试标签也可以正常工作,并且可以看到绑定值。
我需要做什么才能使我的 CustomView 显示可绑定内容?