Reputation: 863
How is this possible? While watching a video on EF5 & WPF, the instructor MAGICALLY pulled the ID of a domain object from a WPF ListBox. And, yes, this does appear to be magic. Here's why...
In the Window_Loaded event handler, she bound the ItemsSource to a ObservableCollection from EF5:
customerListBox.ItemsSource = _repository.CustomersInMemory();
In the customerListBox_SelectionChanged event handler she casts the SelectedValue to the ID of the Customer object, which is an int:
_currentCustomer = _repository.GetCustomerGraph(
((int)customerListBox.SelectedValue)
);
To confirm, this int is NOT the index of the object. As you can see in the receiving method, this is the ID of the Customer object:
public Customer GetCustomerGraph(int id)
{
return _context.Customers.Include(c => c.ContactDetail)
.Include(c => c.Orders)
.FirstOrDefault(c => c.CustomerId == id);
}
To help add to the confusion, there is no property named ID or any attributes in the Customer class. The ID of the customer is actually:
public int CustomerId { get; set; }
How in the world was WPF intelligent enough to know that this is the ID of the Customer object? Is it because the CustomerId is the only int property of the object? If this is so, then what happens the object contains more than one int property?
Please help end my confusion.
For reference, the course is...
Pluralsight: "Getting Started with Entity Framework 5" by Julie Lerman, section 6 ("Using EF in Your Solutions"), part 9 ("Using your EF Data Layer in a Client App (WPF): Debugging and Profiling")
Upvotes: 1
Views: 429
Reputation: 12315
If I have'nt misunderstood the question
_currentCustomer = _repository.GetCustomerGraph(
((int)customerListBox.SelectedValue)
);
Here CustomerListBox.SelectedValue is giving the CustomerID of the Customer ,For this there will be SelectedValuePath set to CustomerID in xaml.
ListBox has properties
SelectedItem : This Property gives one of the item in ItemSource that is Selected.This doesnt return ListBoxItem but return item of Itemsource.However it is of type object all what we need to do is cast it to appropriate Type
Similary there is a Property SelectedValue this gives the particular property value of the SelectedItem and that particular property is what we give in SelectedValuePath. So In your case SelectedValuePath will be CustomerID and hence SelectedValue will return the CustomerID of SelectedCustomer. Since this Property is of object Type so we need to cast it to appropriate type as in your case it is casted to int.
Upvotes: 2