[英]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. 我今天在这个问题上花费了很长时间,因此我将其发布为问题,然后发布答案,这样您就可以避免与过去183分钟的经历相同的挫败感。
Here's a simple version of my source code (perhaps yours looks like this) 这是我的源代码的一个简单版本(也许您的看起来像这样)
.xaml (view): .xaml(查看):
<ComboBox SelectedItem="{Binding WindDirection}" ItemsSource="{Binding WindDirections}" DisplayMemberPath="DisplayText" IsEditable="False"/>
.cs (ViewModel): .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. 所有代码都可以正常工作,并且相同的(.cs)ViewModel甚至可以在另一个(.xaml)视图中正确显示,但是在该视图中不能正常工作。 The precise problem is that there's no text in the ComboBox when the view is first opened even though DisplayText has a value!
确切的问题是,即使DisplayText有值,第一次打开视图时ComboBox中也没有文本! 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.
断点表明DisplayText值已正确计算,并且一切正常,但第一次打开视图时不会显示该值。
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. 如果在.xaml组合框中使用
DisplayMemberPath
属性- 必须将ItemsSource
属性放在.xaml ...中的SelectedItem
属性之前 ,否则将不显示DisplayMemberPath
值。
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.
这可能无法解决您的问题,但肯定可以解决我的问题……希望这可以缩短您的开发时间。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.