我现在正在尝试使一个 ListView 具有可绑定的自定义单元格。我在 XAML 中将单元格定义为 DataTemplate 下的 ViewCell,在 ListView.ItemTemplate 下使用。
为了简单起见,假设我要在单元格中表示两个字符串。ViewCell 将类似于:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="simpletest.MyPage2">
<ContentPage.Content>
<StackLayout Spacing="10" x:Name="layout" Padding="8,10">
<Label Text="{Binding Something}" />
<ListView x:Name="listView">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}" />
<Label Text="{Binding Price}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
我非常非常希望能保持在XAML中。我不想通过在C#中编写整个内容来使其变得臃肿。
我为此页面创建了一个ViewModel,并在代码后台文件中设置了绑定上下文。我的问题是,我是否需要在C#中定义一个扩展ViewCell的类来绑定数据?如上所述,我不想在C#中定义布局。我想以这种方式绑定。我想避免引用字段,因为代码后台文件往往会引用组件。这可行吗?我查看了Xamarin网站,示例使用了代码后台和XAML的混合(如果我理解正确的话...)。
编辑1:
我尝试编写一个模仿一些示例的文件,但这还不够。没有任何代码片段说明这个文件是代表XAML中的ViewCell的文件,也没有明显的方法可以让我通过绑定来填充列表,而不必访问代码后台中的列表字段。如果我只想使用绑定将一些项目添加到此列表中,我错过了什么?
public class ReportedAssignmentCell : ViewCell
{
public ReportedAssignmentCell()
{
}
public static readonly BindableProperty NameProperty = BindableProperty.Create("Name", typeof(string), typeof(ReportedAssignmentCell), "");
public static readonly BindableProperty PriceProperty = BindableProperty.Create("Price", typeof(string), typeof(ReportedAssignmentCell), "");
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
public string Price
{
get { return (string)GetValue(PriceProperty); }
set { SetValue(NameProperty, value); }
}
}
ViewCell
,那么可以在 C# 代码中进行扩展并在 XAML 中引用它,但这并不是必须的,你可以完全像上面所做的那样。你是否遇到了具体的问题? - hvaughan3