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.
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>
Try
IsSynchronizedWithCurrentItem="False"
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>
remove IsSynchronizedWithCurrentItem="True" an add it with the next SelectionChanged event if needed. This solved my problem
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With