Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从WPF列表框中获取SelectedValue的对象ID_C#_Wpf_Entity Framework - Fatal编程技术网

C# 从WPF列表框中获取SelectedValue的对象ID

C# 从WPF列表框中获取SelectedValue的对象ID,c#,wpf,entity-framework,C#,Wpf,Entity Framework,这怎么可能?在EF5和WPF上观看视频时,讲师神奇地从WPF列表框中提取域对象的ID。而且,是的,这看起来确实很神奇。这就是为什么 在窗口加载的事件处理程序中,她将ItemsSource绑定到来自EF5的ObservableCollection: customerListBox.ItemsSource = _repository.CustomersInMemory(); 在customerListBox\u SelectionChanged事件处理程序中,她将SelectedValue强制转换

这怎么可能?在EF5和WPF上观看视频时,讲师神奇地从WPF列表框中提取域对象的ID。而且,是的,这看起来确实很神奇。这就是为什么

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

customerListBox.ItemsSource = _repository.CustomersInMemory();
在customerListBox\u SelectionChanged事件处理程序中,她将SelectedValue强制转换为Customer对象的ID,该ID为int:

_currentCustomer = _repository.GetCustomerGraph(
                      ((int)customerListBox.SelectedValue)
                      );
要确认,此int不是对象的索引。正如您在receiving方法中看到的,这是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究竟是如何聪明到知道这是客户对象的ID的?是否因为CustomerId是对象的唯一int属性?如果是这样,那么对象包含多个int属性会发生什么情况

请帮我结束我的困惑

作为参考,本课程是


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

如果我没有误解这个问题的话

_currentCustomer = _repository.GetCustomerGraph(
                  ((int)customerListBox.SelectedValue)
                  );
此处CustomerListBox.SelectedValue提供客户的CustomerID,因此在xaml中将SelectedValuePath设置为CustomerID

ListBox具有属性

SelectedItem:此属性提供所选ItemSource中的一个项。此属性不返回ListBoxItem,而是返回ItemSource的项。但是它属于object类型。我们需要做的就是将其强制转换为适当的类型

类似地,也有一个属性SelectedValue,它给出SelectedItem的特定属性值,该特定属性就是我们在SelectedValuePath中给出的。因此,在您的情况下,SelectedValuePath将是CustomerID,因此SelectedValue将返回SelectedCustomer的CustomerID。因为这个属性是对象类型,所以我们需要将它转换为适当的类型,就像在您的例子中,它转换为int一样


哇!很明显。。。对于不是WPF noob的人。非常感谢你。我爱WPF!:)