从WPF ListBox获取SelectedValue的对象ID

时间:2013-12-28 18:21:43

标签: c# wpf entity-framework

这怎么可能?在EF5&amp ;;上观看视频时WPF,讲师MAGICALLY从WPF ListBox中提取了域对象的ID。而且,是的,这看起来确实很神奇。这就是为什么......

在Window_Loaded事件处理程序中,她将ItemsSource绑定到来自EF5的ObservableCollection:

customerListBox.ItemsSource = _repository.CustomersInMemory();

在customerListBox_SelectionChanged事件处理程序中,她将SelectedValue转换为Customer对象的ID,这是一个int:

_currentCustomer = _repository.GetCustomerGraph(
                      ((int)customerListBox.SelectedValue)
                      );

要确认,此int不是对象的索引。正如您在接收方法中看到的,这是Customer对象的ID:

public Customer GetCustomerGraph(int id)
{
  return _context.Customers.Include(c => c.ContactDetail)
    .Include(c => c.Orders)
    .FirstOrDefault(c => c.CustomerId == id);
}

为了帮助增加混淆,Customer类中没有名为ID的属性或任何属性。客户的ID实际上是:

public int CustomerId { get; set; }

世界上WPF的智能程度如何才能知道这是Customer对象的ID?是因为CustomerId是对象的唯一int属性吗?如果是这样,那么对象包含多个int属性会发生什么?

请帮忙结束我的困惑。

作为参考,课程是......

Pluralsight:Julie Lerman撰写的“Entity Framework 5入门”,第6部分(“在解决方案中使用EF”),第9部分(“在客户端应用程序中使用EF数据层(WPF):调试和分析” )

1 个答案:

答案 0 :(得分:2)

如果我没有误解这个问题

_currentCustomer = _repository.GetCustomerGraph(
                  ((int)customerListBox.SelectedValue)
                  );
  

此处CustomerListBox.SelectedValue提供Customer的CustomerID,为此,将在Xenam中将SelectedValuePath设置为CustomerID。

ListBox具有属性

  

SelectedItem:此属性为ItemSource中的一个项目提供了Selected.This不返回ListBoxItem但返回Itemsource的项目。但是它是object类型所有我们需要做的是将它强制转换为适当的类型

     

类似地,有一个Property SelectedValue,它给出了SelectedItem的特定属性值,并且该特定属性是我们在SelectedValuePath中提供的。因此,在您的情况下,SelectedValuePath将是CustomerID,因此SelectedValue将返回SelectedCustomer的CustomerID。由于此属性是对象类型,因此我们需要将其强制转换为适当的类型,因为它会转换为int。