WPF學習日誌 ~ 選擇顏色的 ListBox ~

摘要:WPF學習日誌 ~ 選擇顏色的 ListBox ~

在以往Windows Form的應用程式中,ListBox裡面能夠放什麼呢?第一個直覺就是"字",如果要每個Item都各自擁有各自的顏色,那還要自行去處理繪製的動作, 而處理繪製的動作時可能又會讓選取項目的時候失去選取項目時的"醒目提示"(背景變成藍色,表示被選取的狀態),到了WPF這樣的情形獲得很大的改善
下面這個範例所做出來的是一個選擇顏色用的ListBox,像是下面這張圖

從這個範例我們也可以看出WPF的"控制項"可塑性相當的高,下面我們就來看看程式碼吧

 
Imports System.IO
Imports System.Reflection

Class Window1
    Dim sp As StackPanel
    Dim lstColor As ListBox

    Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        ''初始化用來放置Listbox的容器
        sp = New StackPanel
        Me.Content = sp
        lstColor = New ListBox
        lstColor.Margin = New Thickness(5)
        lstColor.MaxHeight = 300
        lstColor.MaxWidth = 300
        ''Form調整大小的模式設定為內含物件的高度
        Me.SizeToContent = Windows.SizeToContent.Height
        ''使用Reflection取得顏色相關的資料
        Dim propInfo() As PropertyInfo
        propInfo = GetType(Colors).GetProperties

        For Each prop As PropertyInfo In propInfo
            ''宣告要放到Listbox中做為Listboxitem的容器
            Dim chSp As New StackPanel
            Dim Rect As New Rectangle
            Dim L As New Label
            L.Content = prop.Name
            Rect.Width = 30
            Rect.Height = 15
            Rect.Fill = New SolidColorBrush(prop.GetValue(Nothing, Nothing))
            Rect.Stroke = SystemColors.WindowTextBrush
            Rect.Margin = New Thickness(2)
            ''設定stackpanel的排列方向為水平
            chSp.Orientation = Orientation.Horizontal
            chSp.Children.Add(Rect)
            chSp.Children.Add(L)
            lstColor.Items.Add(chSp)
        Next
        sp.Children.Add(lstColor)
        ''事件掛載
        AddHandler lstColor.SelectionChanged, AddressOf ListBox_SelectionCheaned
    End Sub

    Protected Sub ListBox_SelectionCheaned(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
        Me.Background = CType( _
                            CType( _
                                CType(e.OriginalSource, ListBox).SelectedItem,  _
                            StackPanel).Children(0),  _
                        Rectangle).Fill
    End Sub
End Class