First of all, I would strongly recommend to remove the member
SelectedUsername
at all. This is an upside-down design and also the violation of the very basic principle "Single Point of Truth". (I cannot refer to "Don't Repeat Yourself"), because you are repeating, but not yourself, but already existing functionality. It also violates natural composition semantics.
Instead, handle selected object outside of the combo box. The property
SelectedUsername
(
instance property!, semantically, has nothing to do with any of the particular instances of the class
Person
. It really belongs to the combo box, nothing else. Strictly speaking, it could be a property of the class derived from
ComboBox
, but this would be a great overkill. Much simpler, you can just get the selected object:
Person selectedPerson = (Person)myComboBox.SelectedItem;
Yes, as simple as that.
There is another (potential?) problem in your code. I would strongly advise you to override
System.Object.ToString()
in your
Person
class. What to return? Whatever you want to show on screen in the item, when the instance of this class is added to a list box, combo box, and the like. Could be a
Name
,
Surname
,
Username
, any combination of them in some format, whatever you want. I cannot see where you take care about this string in your XAML, so this easy-to-write overridden function could be handy in this and many other cases.
See also:
http://msdn.microsoft.com/en-us/library/system.windows.controls.combobox%28v=vs.110%29.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.selecteditem%28v=vs.110%29.aspx[
^],
http://en.wikipedia.org/wiki/Single_Point_of_Truth[
^],
http://en.wikipedia.org/wiki/Don%27t_repeat_yourself[
^].
—SA