好的,我查看了其他问题,似乎没有得到我的答案,所以希望有人在这里.
非常简单的问题为什么DisplayMemberPath属性不绑定到项目?
<ComboBox Grid.Row="1" Grid.Column="2" ItemsSource="{Binding PromptList}" DisplayMemberPath="{Binding Name}" SelectedItem="{Binding Prompt}"/>
Run Code Online (Sandbox Code Playgroud)
跟踪输出显示它正在尝试绑定到持有IEnumerable的类而不是IEnumerable中的实际项.我很困惑一个简单的方法来填充一个组合框而不在xaml中添加一串线.
它只是在itemssource中为对象调用ToString().我有一个解决方法是:
<ComboBox Grid.Row="1" Grid.Column="2" ItemsSource="{Binding PromptList}" SelectedItem="{Binding Prompt}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)
但在我看来,对于这么简单的任务来说太过分了.我可以使用relativesource绑定吗?
您没有绑定到类中的数据,您告诉它从成员"name"命名的类成员中获取数据,因此,如果您的实例item.Name == "steve" 正在尝试从中获取数据item.steve.
为此,您应该从MemberPath中删除绑定.将其更改为MemberPath = "Name" this告诉它从成员"Name"获取数据.这样它会打电话item.Name,而不是item.steve.
您可以删除DisplayMemberPath,然后在TextBlock中设置路径.
当没有ItemTemplate时,DisplayMemberPath就是真的.
或者你可以删除你的ItemTemplate并使用DisplayMemberPath - 在这种情况下它基本上为你创建一个TextBlock.不建议你做两件事.
<TextBlock text="{Binding Path=Name, Mode=OneWay}"
Run Code Online (Sandbox Code Playgroud)