Vjendra Gaorh
Vjendra Gaorh

Reputation: 328

how to avoid first item selection by default in wpf Listbox?

I want to avoid first item selection that happens by default in Listbox when application loads. I tried with

SelectedIndex= -1

but it did not work. I do not want any item to be selected when ListBox loads until user selects any item from Listbox. I have IsSynchronization set to true but making it false also do not solve my problem. Though i have to keep IsSychronization set to true always. But thats ok. i did google but could not find any relevant answer.

Can anyone tell me how to do this ?

Upvotes: 10

Views: 5480

Answers (2)

Ken Budris
Ken Budris

Reputation: 229

I had this happen to me. When I bound ListBox.ItemsSource directly to a collection in my view model, the re was nothing selected by default.

When I switched to using a CollectionViewSource as the ListBox.ItemsSource, suddenly the first item was getting selected by default.

It turns out this was due to ListBox.IsSynchronizedWithCurrentItem. Setting that to

IsSynchronizedWithCurrentItem="False"

on the ListBox restored the desired behavior of having nothing selected by default.

Upvotes: 22

ΩmegaMan
ΩmegaMan

Reputation: 31606

Bind IsEnabled to a boolean which will flag when the user can then select. The listbox will still be visible but non selectable. Here is style code for a label I use where it has to be enabled during login, but not once the operation stops.

  <Style x:Key="LabelStyle" TargetType="{x:Type Label}">
        <Setter Property="VerticalAlignment" Value="Center" />
        <Setter Property="Width" Value="70" />
        <Setter Property="Height" Value="28"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=LoginInProcess}" Value="True">
                <Setter Property="IsEnabled" Value="False" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Path=LoginInProcess}" Value="False">
                <Setter Property="IsEnabled" Value="True" />
            </DataTrigger>
        </Style.Triggers>
    </Style>

Upvotes: 0

Related Questions