因此,在后面的代码中,我从sqlite数据库中提取并创建具有各种属性的人员列表。我想将Name属性附加到按钮的文本。这是背后代码中的对象(我在OnAppearing方法中拥有它):
List<Person> People = await App.PersonRep.GetAllPeople();
我试图将此列表中的特定索引绑定到XAML中的按钮,但正在努力寻找可行的解决方案。将按钮放在列表视图中是唯一的方法吗?我希望做一些看起来更干净或更简单的事情
编辑更多代码:
<ContentPage.Content>
<ListView x:Name="peopleList">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell Height="30">
<StackLayout Padding="5">
<Button Text="{Binding People[0].PersonName}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage.Content>
然后在后面的代码中:
public List<Person> People { get; set; }
protected override void OnAppearing()
{
PopulatePeople();
}
public async void PopulatePeople()
{
List<Person> People = await App.PeopleRepo.GetAllPeople();
peopleList.ItemsSource = People;
然后这是PeopleRepository类中的GetAllPeople方法(也在App类中创建了PeopleRepository类型的PeopleRepo对象):
public SQLiteAsyncConnection conn;
public PeopleRepository(string db)
{
conn = new SQLiteAsyncConnection(db);
conn.CreateTableAsync<Person>().Wait();
}
public async Task<List<Person>> GetAllPeople()
{
try
{
return await conn.Table<Person>().ToListAsync();
}
catch (Exception ex)
{
Status = string.Format("Failed to retrieve data. {0}", ex.Message);
}
return new List<Person>();
}
答案 0 :(得分:2)
您可以在绑定路径中使用[]来引用索引
在您的代码中
//you can only bind to public properties
public List<Person> People { get; set; }
在您的XAML中
<Label Text="{Binding People[10].Name}" />
答案 1 :(得分:0)
有几种方法可以解决此问题。
一种方法是创建一个组合框,并将列表分配为ItemsSource
。然后,您可以制作一些标签并输入并在组合框中将所选人员分配为窗口的DataContext
。
例如,这是XAML:
<ComboBox x:Name="personCombobox" HorizontalAlignment="Left" SelectionChanged="personCombobox_OnSelectionChanged">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding FirstName, Mode=OneWay}" />
<TextBlock Text=" - " />
<TextBlock Text="{Binding LastName, Mode=OneWay}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Label Content="{Binding FirstName, Mode=OneWay}"/>
<Label Content="{Binding LastName, Mode=OneWay}" />
然后,后面的代码将如下所示:
public MainWindow()
{
InitializeComponent();
personCombobox.ItemsSource = personRepository.GetAll();
personCombobox.SelectedIndex = 0;
}
private void personCombobox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (personCombobox.SelectedIndex != -1)
{
this.DataContext = (Person)personCombobox.Items.GetItemAt(personCombobox.SelectedIndex);
}
}