我有一个 ASP.NET Web API,根据我的测试它可以正常工作。现在,我想在一个简单的 WPF 应用程序中使用它。我只想从 API 获取数据,将其显示在客户端应用程序中,然后仅使用客户端应用程序从数据库中添加或删除数据。
我的问题是,当我将数据传递给 a 时ListBox
,我会丢失信息,特别是我丢失Id
了对象的 ,稍后我需要这些信息才能从数据库中删除它。在我的场景中,我的其中一个页面中有这样的内容:
<ListBox
Name="carCategoryListBox"
Grid.Row="2"
Grid.Column="1" />
然后,在.cs
页面文件中,我执行以下操作:
private void Page_Loaded(object sender, RoutedEventArgs e)
{
BindCarCategoryList();
}
private async void BindCarCategoryList()
{
var client = CarHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("api/carcategories");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var carCategories = JsonConvert.DeserializeObject<List<DTO.CarCategory>>(content);
carCategoryListBox.ItemsSource = carCategories.Select(cc => cc.Category).ToList();
}
else
{
MessageBox.Show("Error code " + response.StatusCode + "\nMessage - " + response.ReasonPhrase);
return;
}
}
如您所见,我只是获取Category
对象的字段,并将它们传递ListBox
给要显示的 。该CarCategory
班是非常简单,可以看到下面:
public class CarCategory
{
public int Id { get; set; }
public string Category { get; set; }
}
问题是在稍后阶段我需要获取Id
对象的实际值并使用它。但是,由于我只将Category
字段传递给ListBox
,因此Id
在我的情况下,此信息以某种方式丢失了。如果我做这样的事情:
int id = carCategoryListBox.SelectedIndex;
然后,我只是获得了(它在列表Id
中的ListBox
哪个项目)中的项目,我实际上并没有获得Id
存储在数据库中的对象的原件。任何想法如何将数据传递给 aListBox
以某种方式仍然保留原始Id
信息?
ListBox.SelectedIndex
是 ItemsSource 中所选项目的位置。如果没有选中的项目,它甚至可以是 -1。它与价值不同Id
要获取数据绑定对象,请进行一些更改:
1)List<CarCategory>
用作ItemsSource:
carCategoryListBox.ItemsSource = carCategories;
2) 为其设置 ListBox.DisplayMemberPath 以显示类别名称:
<ListBox DisplayMemberPath="Category"
Name="carCategoryListBox"
Grid.Row="2"
Grid.Column="1" />
3) 使用SelectedItem
属性来获取选定的项目(可以是null
):
var category = (CarCategory)carCategoryListBox.SelectedItem;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句