Reputation: 51
I spent so long on this issue today that I'm posting it as a question and then posting the answer so that you can avoid the same kind of frustration that I've gone through for the past 183 minutes.
Here's a simple version of my source code (perhaps yours looks like this)
.xaml (view):
<ComboBox SelectedItem="{Binding WindDirection}" ItemsSource="{Binding WindDirections}" DisplayMemberPath="DisplayText" IsEditable="False"/>
.cs (ViewModel):
public class WindDirectionViewModel{
//I realize that there may be problems in this code, it's not my real code, just a quick sample
...code
List<WindDirectionObject> WindDirections = new List<WindDirectionObject>();
WindDirectionObject WindDirection = new WindDirectionObject();
...code
public string DisplayText = WindDirections.First(x => x.Equals(WindDirection)).DisplayString;
...code
}
All of the code works perfectly and the same (.cs) ViewModel is even displayed correctly in another (.xaml) view, but in this view it isn't working correctly. The precise problem is that there's no text in the ComboBox when the view is first opened even though DisplayText has a value! Breakpoints show that the DisplayText value is being correctly calculated and everything, but the value won't display when the view is opened the first time.
Upvotes: 0
Views: 935
Reputation: 51
If you are using the DisplayMemberPath
attribute in a .xaml combo box - you must place the ItemsSource
attribute before the SelectedItem
attribute in the .xaml... or the DisplayMemberPath
value isn't displayed.
Before:
<ComboBox ItemsSource="{Binding WindDirections}" SelectedItem="{Binding WindDirection}" DisplayMemberPath="DisplayText" IsEditable="False"/>
After:
<ComboBox SelectedItem="{Binding WindDirection}" ItemsSource="{Binding WindDirections}" DisplayMemberPath="DisplayText" IsEditable="False"/>
Bam. Works perfectly. This may not solve your problem, but it certainly solved mine...hope this speeds up your development time. :)
Upvotes: 1