Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListBox always auto selects first item

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

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

like image 795
Shimmy Weitzhandler Avatar asked Sep 09 '09 09:09

Shimmy Weitzhandler


5 Answers

Here's a technique I use quite often. It builds on the above example of adding the FocusedElement attribute to your Window or UserControl.

My deal is that I don't want ANY of the controls on my window to have focus. The solution for me is to create a dummy control that has no UI and assign focus to that. It just so happens that Control fits the bill perfectly:

<UserControl
    x:Class="MyControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FocusManager.FocusedElement="{Binding ElementName=focus_thief}"
    mc:Ignorable="d">
    <Grid>
        <!-- no renderable UI -->
        <Control Name="focus_thief"/>
        <!-- wants focus, but won't get it -->
        <ListBox>
            <ListBoxItem>First Item</ListBoxItem>
        </ListBox>
    </Grid>
</UserControl>
like image 165
rmirabelle Avatar answered Nov 05 '22 04:11

rmirabelle


Try

IsSynchronizedWithCurrentItem="False"

like image 27
Joe Avatar answered Nov 05 '22 06:11

Joe


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>
like image 39
Madi D. Avatar answered Nov 05 '22 05:11

Madi D.


remove IsSynchronizedWithCurrentItem="True" an add it with the next SelectionChanged event if needed. This solved my problem

like image 30
smeissner Avatar answered Nov 05 '22 06:11

smeissner


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

like image 4
Thomas Levesque Avatar answered Nov 05 '22 04:11

Thomas Levesque