如何從數據綁定的ListBox中獲取ListBoxItem?
原文出處:http://www.beacosta.com/Archive/2005_09_01_bcosta_archive.html在WPF中數據綁定一個(gè)ListBox到一個(gè)列舉物品并不是那么容易.
<Window.Resources>
<local:GreekGods x:Key="greekGods"/>
<DataTemplate x:Key="itemTemplate">
<TextBlock Text="{Binding Path=Name}" />
</DataTemplate>
</Window.Resources>
<ListBox ItemsSource="{StaticResource greekGods}" ItemTemplate="{StaticResource itemTemplate}" Name="listBox"/>
ListBox的ItemSource屬性有一個(gè)IEnumerable,就是你想要顯示的物體列表.在這里GreekGods數據源是ObservableCollection(繼承自IEnumerable)類(lèi)型.ItemTemplate屬性指定DataTemplate,DataTemplate是用來(lái)控制如何顯示數據的.在這個(gè)例子中,每一項都有一個(gè)TextBlock來(lái)顯示GreekGod的名字.
一些人可能會(huì )很驚訝,因為運行代碼中的ListBox.Items[i]會(huì )返回我們所綁定的數據而不是TextBlock或者ListBoxItem.我覺(jué)得,能夠 很容易的從ListBox中獲取到特定位置的數據是很酷的,因為這是我們通常想要的.
GreekGod greekGod = (GreekGod)(listBox.Items[0]);
但是當你確實(shí)想獲取產(chǎn)生的ListBoxItem時(shí)該如何做呢?這個(gè)有一些小竅門(mén)去發(fā)掘,但是利用下面的代碼也很容易做到:
ListBoxItem lbi1 = (ListBoxItem)(listBox.ItemContainerGenerator.ContainerFromIndex(0));
另外ListBox.ItemContainerGenerator.ContainerFromItem(object item)通過(guò)指定item也能返回ListBoxItem.這個(gè)方法很經(jīng)常使用到,例如,從CurrentItem獲取ListBoxItem:
ListBoxItem lbi2 = (ListBoxItem)(listBox.ItemContainerGenerator.ContainerFromIndex(listBox.Items.CurrentItem));
我將會(huì )在以后的帖子中詳細的介紹selection和current item.但在這個(gè)例子中,這個(gè)還是很有必要知道的,為了保持selection和current item的同步性,我設置了ListBox的IsSynchronizedWithCurrentItem="true".

由于原來(lái)作者的代碼比較早期,vs更新后無(wú)法編譯了.自己小小修改以下:

share your files at box.net

