Thursday, August 6, 2009

Scrolling a Disabled Listbox in WPF

Recently I had a requirement when developing an application,where i needed a listbox which was to be disabled but yet can be scrolled,so that all the contents in it was visible.Applying the property,IsEnabled=False makes the whole listbox disabled even disabling the scroll.
I just found out a way around this.I created a custom listbox(MyScrollableListbox) with a property IsItemsEnabled.Setting this property to true,gives the normal listbox behaviour.When set to false only the ItemsPresenter of the listbox is disabled,so that scrolling is possible

The Custom Listbox looks like this(just one property added for now)


Public Class MyScrollableListbox
Inherits ListBox

Public Property IsItemsEnabled() As Boolean
Get
Return GetValue(IsItemsEnabledProperty)
End Get

Set(ByVal value As Boolean)
SetValue(IsItemsEnabledProperty, value)
End Set
End Property

Public Shared ReadOnly IsItemsEnabledProperty As DependencyProperty = _
DependencyProperty.Register("IsItemsEnabled", _
GetType(Boolean), GetType(MyScrollableListbox), _
New FrameworkPropertyMetadata(Nothing))

End Class


In the xaml(or if you are going to make it a custom control then you can give it in your Generic.xaml)


 <Grid>
        <local:MyScrollableListbox x:Name="ListBox1"   Margin="41,35,0,0" Height="83" HorizontalAlignment="Left" VerticalAlignment="Top" Width="69">
            <local:MyScrollableListbox.Style>
                <Style TargetType="{x:Type local:MyScrollableListbox}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate>
                                <Border>
                                    <ScrollViewer>
                                        <ItemsPresenter IsEnabled="{Binding Path=IsItemsEnabled, RelativeSource={RelativeSource TemplatedParent}}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}"/>
                                    </ScrollViewer>
                                </Border>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </local:MyScrollableListbox.Style>
        </local:MyScrollableListbox>
    </Grid>


Now if you set the property IsItemsEnabled to false the listbox will be disabled,but allowing you to scroll.


edit: Added in CodeProject

Hope it helps :)

1 comment:

Note: Only a member of this blog may post a comment.