views:

851

answers:

6

ListBox's behavior is that the first item is selected automatically, how can I avoid that??

Note: I want to do this with pure xaml, if you have any code-behind ideas then please don't bother yourself.

+2  A: 

You could set SelectedIndex to -1 :

<ListBox ItemsSource="{Binding MyData}" SelectedIndex="-1"/>

Note: I want to do this with pure xaml, if you have any code-behind ideas then please don't bother yourself.

Unfortunately you can't do everything in XAML... you can usually avoid code-behind, but you still need to write converters, markup extensions or attached properties

Thomas Levesque
I was lookin for an answer just like yours.the only tiny problem is it doesn't work.
Shimmy
it doesnt work :)
Madi D.
+1, you can't do everything in XAML.
sixlettervariables
The problem is that I want to avoid this since the selection triggers a chain of executions which are processed at the SelecttionChanged handler.
Shimmy
A: 

Is SelectedIndex the property you're looking for ? Or maybe I don't get your point...

Jalfp
you got my point, but when i set selectedindex to -1 or alternatively selected item to x:Null, the first item is still selected
Shimmy
A: 
<ListBox SelectioMode="Single" SelectedIndex="-1"/>
Sauron
I don't want the selection mode to be Single.
Shimmy
+2  A: 

Well i tried this using FocusManager.FocusedElement .. and made the intial focus to
listbox itself.. so it has the focus..but no element is selected.. if u press down or tab ..the 1st element of the listbox will be selected...

<Window
...... 
FocusManager.FocusedElement="{Binding ElementName=listbox2}">
    <ListBox x:Name="listbox2" HorizontalAlignment="Left"
        VerticalAlignment="Bottom" Width="117.333" Height="116" 
        Margin="30.667,0,0,30">
        <ListBoxItem>Jim</ListBoxItem>
        <ListBoxItem>Mark</ListBoxItem>
        <ListBoxItem>Mandy</ListBoxItem>
</ListBox>
Madi D.
A: 

Add a blank item.

Jeremy Stein
A: 

Same issue here. Anyone found a "clean" solution?
The problem is the same here, it causes a bunch of triggers to execute.

Obvious solution/fix:
1) Remove SelectionChanged event handlers from XAML
2) Add handlers in constructor after InitializeComponents has loaded the listbox.

Bodekaer
Related questions and comments shuold be comments on the existing one.
Shimmy