Reputation: 104711
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.
Upvotes: 12
Views: 17191
Reputation: 331
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:
Upvotes: 1
Reputation: 6446
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>
Upvotes: 4
Reputation: 51
remove IsSynchronizedWithCurrentItem="True" an add it with the next SelectionChanged event if needed. This solved my problem
Upvotes: 5
Reputation: 1990
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>
Upvotes: 7
Reputation: 6718
Is SelectedIndex the property you're looking for ? Or maybe I don't get your point...
Upvotes: 1
Reputation: 292405
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
Upvotes: 4