如何在wpf中冻结列表框的第一项?

时间:2013-01-16 04:36:19

标签: wpf xaml listbox listboxitem

我有一个带有单选按钮的列表框作为其项目。列表框是可滚动的,可以添加尽可能多的项目。但是,我必须保持第一个项目冻结,因为它应该始终可见。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

有点棘手。您可以编辑Listbox的模板,并在scrollviewer上方添加ListBoxItem。像

这样的东西
<Style x:Key="ListBoxTopItemFixedStyle" TargetType="{x:Type ListBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBox}">
                    <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="1" SnapsToDevicePixels="true">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"/>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>

                            <ListBoxItem Content="{Binding Path=FreezeItem.PropertyName, 
                                                    RelativeSource={RelativeSource AncestorType={x:Type Window}}}" 
                                         Grid.Row="0"/>
                            <ScrollViewer Focusable="false" Padding="{TemplateBinding Padding}"  Grid.Row="1">
                                <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                            </ScrollViewer>
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                        </Trigger>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="IsGrouping" Value="true"/>
                                <Condition Property="VirtualizingPanel.IsVirtualizingWhenGrouping" Value="false"/>
                            </MultiTrigger.Conditions>
                            <Setter Property="ScrollViewer.CanContentScroll" Value="false"/>
                        </MultiTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

我还使用了FreezeItem,它是控件上下文中的一个项目。您可以使用相同的概念并根据需要进行修改。如果你想避免使用FreezeItem,你也可以使用转换器获取第一个收集项。