2011年8月21日

[WPF][C#] - ListBox 鏈結自訂ListItem類別

當有一個二維陣列的資料想要放進ListBox裡要怎麼做呢?

在Asp.net有Items.Value及Items.Text可以應用

在Form該怎麼處理呢?

上網查了一下.有兩種方法
第一種:建立一個DataTable去建立columns再用
listbox.ItemsSource=table;

第二種:透過自訂的ListItem類別來達成,這是今天要介紹的部分。

首先,我們要先建立一個自訂的ListItem類別讓ListBox鏈結.

public class ListUnit
        {
            public string no { set; get; }
            public string name { set; get; }
            public ListUnit(string _no, string _name)
            {
                this.no = _no;
                this.name = _name;
            }
        }

接下來做ListBox新增資料的動作.
listbox1.Items.Add(new ListUnit("1","Test");

最後,設定顯示的資料行,這樣就大功告成了!
listbox1.DisplayMemberPath = "name";

最後再提一下取值得部分,也很簡單!
(listbox1.SelectedValue as ListUnit).no


其實做自訂的ListItem不難,看使用的地方。

實作在ListBox因為有顯示的問題,所以才要自訂ListItem類別,這樣才能做設定顯示的功能!

若是在ArrayList的話,我會使用Struct來做就行了,就不必搞得這麼麻煩。

沒有留言:

張貼留言