2012-04-18 47 views
2

我想了解如何使用數組的ItemSourceC#WPF列表框dispaly多個memberpath

到目前爲止,我可以用一個價值管理在列表框中顯示更多的價值,但無法弄清楚如何顯示多個值:

代碼:

 listBox1.ItemsSource = toReturn.groups; 
     listBox1.DisplayMemberPath = "name"; 

toReturn.Groups是項目陣列;每個項目都有一個ID和一個名字。

我希望能夠同時顯示兩者。你爲什麼不創建一個名爲顯示

public string Display { 
    get { 
     return String.Format("{0} - {1}", ID, Name); 
    } 
} 

然後在您的項目屬性

+0

我可以看看代碼的其餘部分,我可以幫助你更好。我會舉一個我最近使用過的例子。 – 2012-04-19 14:35:12

回答

1
string uriGroup = "http://localhost:8000/Service/Group"; //rest based http GET 
    private void button14_Click(object sender, EventArgs e) 
    { 
    XDocument xDoc = XDocument.Load(uriGroup); //Load the uri into the xdoc 
    var groups = xDoc.Descendants("Group") //descendants of xml query "Group" 
     .Select(n => new 
     { 
      GroupID = n.Element("GroudID").Value, 
      Group = n.Element("GroupName").Value, //first "Group" Sets the column title, second sets the Element to be listed in this case "GroupName" from my service. 

     }) 
     .ToList(); 

    dataGridView2.DataSource = groups; 

Ofcourse我使用一個DataGrid,但我相信同樣可以爲列表框的工作?希望這可以幫助Davide。

2

只是做:

listBox1.DisplayMemberPath = "Display"; 
2

或者,你可以申請一個DataTemplate你的列表框的項目,以獲得更多的控制權瞭解它們的顯示方式,而不是將冗餘屬性添加到視圖模型中。請在這裏找到一個例子:http://www.wpftutorial.net/ListBoxDataTemplate.html