一个非常简单的绑定如何用于 ListView 中的 Label?
我似乎已经花了几个小时,但无法弄清楚。
标签的数据绑定有什么问题?
因为显示了三行,这意味着 Observable 集合View Model
已被绑定。
我是否过度使用 x:DataType 是否真的需要简单的网格绑定?
XAML 文件
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="Poc.ListViewGrouping.Views.LvDemo"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Poc.ListViewGrouping.ViewModels"
xmlns:model="clr-namespace:Poc.ListViewGrouping.Models">
<ContentPage.Content>
<StackLayout>
<Label
HorizontalOptions="CenterAndExpand"
Text="Welcome to Abhijeet's Page Of List View!"
VerticalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage.Content>
<ContentPage.ToolbarItems>
<ToolbarItem Command="{Binding AddItemCommand}" Text="Add Milestone" />
</ContentPage.ToolbarItems>
<RefreshView x:DataType="local:Lv1Vm">
<StackLayout BackgroundColor="Orange">
<ListView
x:Name="lv1"
BackgroundColor="Green"
ItemsSource="{Binding DS}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:Lv1Vm">
<ViewCell>
<Frame BackgroundColor="Navy">
<StackLayout
Padding="10"
x:DataType="model:LvModel"
BackgroundColor="Yellow"
HeightRequest="30">
<!-- Does not bind at all -->
<Label BackgroundColor="Red"
Text="{Binding Name}" />
</StackLayout>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</RefreshView>
</ContentPage>
代码隐藏文件
using Poc.ListViewGrouping.ViewModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Markup;
using Xamarin.Forms.Xaml;
namespace Poc.ListViewGrouping.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LvDemo : ContentPage
{
public Lv1Vm _viewModel;
public LvDemo()
{
BindingContext = _viewModel = new Lv1Vm();
InitializeComponent();
}
}
}
查看模型
using Poc.ListViewGrouping.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
namespace Poc.ListViewGrouping.ViewModels
{
public class Lv1Vm : BaseViewModel
{
public ObservableCollection<LvModel> DS => new ObservableCollection<LvModel>()
{
new LvModel{Id = 1, Name = "Hello" },
new LvModel{Id = 2, Name="Hi"},
new LvModel{Id = 3, Name="Good Going"},
};
public Lv1Vm()
{
Title = "Lv1";
}
}
}
模型
public class LvModel
{
public string Name { get; set; }
public int Id { get; set; }
}