WPF 自定義ListBox


 如題,要實現一個如下的列表,該如何實現?

在設計過程中,會遇到如下問題:

1、ListBox中ListBoxItem的模板設計

2、ListBox中ListBoxItem的模板容器設計

3、ListBox本身的模板設計

4、ListBox本身的焦點樣式

下面我們依次來解決這些問題:

1、子模板

 <ListBox.ItemTemplate>
                 <DataTemplate>
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
                        <CheckBox IsChecked="{Binding IsChecked}" Height="20" Width="20" Style="{StaticResource CheckBoxStyle}" VerticalAlignment="Center" Margin="10,5"></CheckBox>
                        <Ellipse Height="14" Width="14" Fill="{Binding Color}"  VerticalAlignment="Center" Margin="5"></Ellipse>
                        <TextBlock Text="{Binding Text}" VerticalAlignment="Center" Margin="5" FontSize="16"></TextBlock>
                    </StackPanel>
                </DataTemplate>
</ListBox.ItemTemplate>

2、ListBoxItem的容器

<Style x:Key="ItemContainer" TargetType="{x:Type ListBoxItem}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <Border  x:Name="IconBorder" Background="White" CornerRadius="4" BorderThickness="0">
                        <ContentPresenter />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="true">
                            <Setter TargetName="IconBorder" Property="BitmapEffect">
                                <Setter.Value>
                                    <OuterGlowBitmapEffect GlowColor="Transparent" GlowSize="5" />
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

3、ListBox的模板

<ListBox.Template>
                <ControlTemplate>
                    <StackPanel Background="White" IsItemsHost="True"></StackPanel>
                </ControlTemplate>
</ListBox.Template>

4、焦點樣式 設置為NULL即可

 <ListBox x:Name="MyListBox" ItemContainerStyle="{StaticResource ItemContainer}" FocusVisualStyle="{x:Null}">
</ListBox> 

 如此,ListBox就設計好了。剩下的就是設計CheckBox和其中子控件的樣式,以及綁定數據。

CheckBox的樣式設計見下一章節-《WPF-自定義CheckBox》


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM