为动态组合框设置DisplayMemberPath [英] Set DisplayMemberPath For Dynamic Combobox

查看:61
本文介绍了为动态组合框设置DisplayMemberPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为WPF Windows应用程序动态创建WPF ComboBox.但是,当我建立一个包含2个项目的类对象的列表并绑定到组合框时,我在组合框中看到了记录,但看不到显示的任何文本.我认为我正在适当地设置DisplayMemberPath.有什么想法吗?

I am creating a WPF ComboBox for a WPF Windows application dynamically. However, when I build a list of a class object with 2 items in the list and bind to the combobox, I see records in the combobox but do not see any text displayed. I am setting the DisplayMemberPath appropriately I think. Any ideas?

Class AnswerChoice
    Public AnswerChoiceID As Integer
    Public AnswerChoice As String
End Class

Private Function GetAnswerChoices() As List(Of AnswerChoice)
     Dim lstAnswerChoices As New List(Of AnswerChoice)
     Dim objAnswerChoice As AnswerChoice

     objAnswerChoice = New AnswerChoice
     objAnswerChoice.AnswerChoiceID = 1
     objAnswerChoice.AnswerChoice = "Answer Choice One"
     lstAnswerChoices.Add(objAnswerChoice)

     objAnswerChoice = New AnswerChoice
     objAnswerChoice.AnswerChoiceID = 2
     objAnswerChoice.AnswerChoice = "Answer Choice Two"
     lstAnswerChoices.Add(objAnswerChoice)

     Return lstAnswerChoices
End Function

Dim ctrlComboBox As New ComboBox()
ctrlComboBox.Width = 300
ctrlComboBox.HorizontalAlignment = Windows.HorizontalAlignment.Left
ctrlComboBox.Name = "cboBox"
ctrlComboBox.ItemsSource = GetAnswerChoices()
ctrlComboBox.DisplayMemberPath = "AnswerChoice"
ctrlComboBox.SelectedValuePath = "AnswerChoiceID"

推荐答案

从讨论区发布.谢谢EriC!

您需要像这样在Class AnswerChoice属性中创建字段

Posted from Discussion Board. Thanks EriC!

You need to make your fields in Class AnswerChoice Properties like this

Dim intAnswerChoiceID As Integer
    Public Property AnswerChoiceID As Integer
        Get
            Return intAnswerChoiceID
        End Get
        Set(ByVal value As Integer)
            intAnswerChoiceID = value
        End Set
    End Property
    Dim strAnswerChoice As String
    Public Property AnswerChoice As String
        Get
            Return strAnswerChoice
        End Get
        Set(ByVal value As String)
            strAnswerChoice = value
        End Set
    End Property  



我的建议还应该是使用ObservableCollection而不是List来存储您的集合,因为如果集合有任何更改,它会通知您的UI.

希望这会有所帮助

当我是编码员时,我们从事算法工作.今天,我们记住了无数库的API-这些库具有算法-Eric Allman



My advice also would be to use an ObservableCollection rather than a List to store your collection, as it notifies your UI if there are any changes to the collection.

Hope this helps

When I was a coder, we worked on algorithms. Today, we memorize APIs for countless libraries — those libraries have the algorithms - Eric Allman


这篇关于为动态组合框设置DisplayMemberPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆