简体   繁体   中英

DisplayMemberPath on ComboBox not working but Binding seems correct, can't get the DisplayMemberPath to display

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.

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. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM