文章目錄
- 簡介
- ListBoxItem
- 選中項目
- 動態列表
簡介
【ListBox】是列表控件,其內部可包含多個【ListBoxItem】,用戶可以從列表中選擇一個或多個項,若Item個數超過指定高度,則右側會自動出現滾動條,非常便捷。盡管邏輯上來說,ListBox里面就應該裝載ListBoxiItem,但實際上也可以裝載其他控件,示例如下
其WPF代碼為
<ListBox x:Name="lbDev" Height="100"><ListBoxItem Content="ListBoxItem A"/><ListBoxItem Content="ListBoxItem B"/><Button Content="Button"/><TextBox Text="TextBox"/><ListBoxItem Content="ListBoxItem C"/>
</ListBox>
ListBoxItem
【ListBoxItem】作為ListBox默認的子控件,其功能相對比較完備,在外觀屬性上,支持顏色、字體以及背景圖片等美化;在動作上,支持雙擊。此外,還可以用其他控件來填充其Content,從而實現更復雜的功能。
下圖分別對A, B, C三個Item進行了定制:為A設計了前景色和文字顏色;為B中添加了圖片;將C封裝成了單選框。
其WPF代碼如下
<ListBox x:Name="lbDev" Height="100"><ListBoxItem Content="ListBoxItem A" Background="LightBlue" Foreground="Purple"/><ListBoxItem><StackPanel Orientation="Horizontal"><Image Source="E:\work\code\doc\imgs\PI_H811.jpg" Height="30"/><TextBlock Text="ListBoxItem B"></TextBlock></StackPanel></ListBoxItem><ListBoxItem><CheckBox Content="ListBoxItem C"/></ListBoxItem>
</ListBox>
其中,B和C都其Content進行了定制,且B中采用了StackPanel布局,理論上講,甚至可以插入一整個頁面。
由于單擊操作被用于選中項目,故ListBoxItem中,用【Selected】來綁定單擊事件,而雙擊操作【MouseDoubleClick】則不受影響,其綁定方式和普通的按鈕沒什么區別,故不再贅述了。
選中項目
之所以采用ListBox,主要原因是其子控件有一定的相似性,所以實際編程中,往往在ListBox這個層次來協調其子控件的選中等操作,示例如下
WPF代碼為
<ListBox x:Name="lbDev" Height="60" SelectionChanged="lbDev_SelectionChanged" MouseDoubleClick="lbDev_MouseDoubleClick" ><ListBoxItem Content="ListBoxItem A"/><ListBoxItem Content="ListBoxItem B"/><ListBoxItem Content="ListBoxItem C"/>
</ListBox>
<TextBox x:Name="tbInfo" Height="50"/>
C#代碼為
private void lbDev_SelectionChanged(object sender, SelectionChangedEventArgs e)
{tbInfo.Text = $"選中第{lbDev.SelectedIndex}個Item";
}private void lbDev_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{tbInfo.Text = $"雙擊第{lbDev.SelectedIndex}個Item";
}
動態列表
ListBox支持動態添加和刪除Item,如下圖所示
其wpf代碼為
<ListBox x:Name="lbDev" Height="60">
</ListBox>
<UniformGrid Columns="3"><TextBox x:Name="tbName"/><Button Content="添加Item" Click="btnAddItem_Click"/><Button Content="刪除Item" Click="btnRmItem_Click"/>
</UniformGrid>
C#代碼為
private void btnAddItem_Click(object sender, RoutedEventArgs e)
{lbDev.Items.Add(new ListBoxItem() { Content = tbName.Text });
}private void btnRmItem_Click(object sender, RoutedEventArgs e)
{lbDev.Items.RemoveAt(lbDev.SelectedIndex);
}
其中【RemoveAt】可以刪除指定位置的Item,也可以用【Remove】刪除指定的Item。此外,【Clear】可以刪除所有Item。