我已经创建了一个可重复使用的组件,用于带有图标和文本的患者卡:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class PatientInfoCard : ContentView
{
public static readonly BindableProperty TitleProperty = BindableProperty.Create(
nameof(Title),
typeof(string),
typeof(PatientInfoCard),
default(string)
);
public string Title
{
get => (string)GetValue(TitleProperty);
set => SetValue(TitleProperty, value);
}
public PatientInfoCard()
{
InitializeComponent();
}
}
其xaml:
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MobileApp.Control.PatientInfoCard">
<ContentView.Content>
<StackLayout Background="green" Padding="10" >
<StackLayout Margin="10,10,10,0" BackgroundColor="gray">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Text="{Binding Title}" FontAttributes="Bold" VerticalOptions="Center" />
<Label Grid.Column="1" Text="{Binding Title}" FontAttributes="Bold" VerticalOptions="Center" />
</Grid>
<Label Text="{Binding Description}" Margin="10,5,10,10" VerticalOptions="CenterAndExpand" />
</StackLayout>
</StackLayout>
</ContentView.Content>
</ContentView>
然后我试着在一个网格中使用它:
<Grid Margin="10" Grid.Row="6" Grid.ColumnSpan="2" RowSpacing="10" ColumnSpacing="10"
x:DataType="Control:PatientInfoCard">
<Control:PatientInfoCard Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" Title="Vaistai"/>
<Control:PatientInfoCard Grid.Row="0" Grid.Column="3" Grid.ColumnSpan="3" Title="Tyrimai" />
<Control:PatientInfoCard Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Title="Ligos"/>
<Control:PatientInfoCard Grid.Row="1" Grid.Column="2" Grid.ColumnSpan="2" Title="Alergijos"/>
<Control:PatientInfoCard Grid.Row="1" Grid.Column="4" Grid.ColumnSpan="2" Title="Skiepai"/>
</Grid>
它只给我5块模板(没有标题和图标):
所以我猜绑定值不能正常工作?我的代码缺少什么?
1条答案
按热度按时间3df52oht1#
从视图的XAML绑定到其自己的代码隐藏的一种方法是为XAML部分定义
x:Name
,例如PatientCard
,然后在绑定中使用x:Reference PatientCard
作为Source
:BindingContext = this;
或设置为ViewModel或Model类: