locked
ListBox.SelectedItem Focus RRS feed

  • Question

  • I am working in Expression Blend 4, and Silverlight and have created a ListBox DataBound to DataSource.

    On loading the page I want one of the ListBoxItems to be preselected.  When I put other than "-1" in the SelectedIndex counter the solution does not build correctly, so this doesn't seem to be the route.

    How can I set an item in the listbox to be selected when the page loads?

    Sunday, January 30, 2011 7:32 PM

All replies

  • I just tried it using the ListBox.Loaded event, and that seems to fire after the items are loaded into the ListBox.

     

    private void ListBoxLoaded(object sender, System.Windows.RoutedEventArgs e)
    		{
    			this.LB.SelectedIndex = 4;
    		}
    
    <UserControl
    	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    	x:Class="SilverlightApplication69.MainPage"
    	Width="640" Height="480">
    	<UserControl.Resources>
    		<DataTemplate x:Key="ItemTemplate">
    			<StackPanel>
    				<TextBlock Text="{Binding Property1}"/>
    				<CheckBox IsChecked="{Binding Property2, Mode=TwoWay}"/>
    			</StackPanel>
    		</DataTemplate>
    	</UserControl.Resources>
    
    	<Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource SampleDataSource}}">
    		<ListBox x:Name="LB" ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding Collection}" Margin="136,80,304,100" SelectedIndex="-1" Loaded="ListBoxLoaded"/>
    	</Grid>
    </UserControl>
    

    Monday, January 31, 2011 2:43 PM
    Moderator
  • Chuck,

     

    Thanks for the reply.

    I tried using the SelectedItem when I set up the listbox, but this didn't work.  I am trying to carry a selected item over from another page and have used a datasource to carry the number across into the listbox selection.  The numbers carry across OK, as shown by a textbox on the screen.  I thought at first it was the datasource that was the problem so replaced it with numbers.  Again it didn't work.

    I have set the site up as frames within a MainPage.  Is the NavigationUri a possible problem?  It took me a while to discover TargetName="_New" to open a window to another site.  Is there a similar trick to set the listbox index?  The listbox index stays selected when I navigate to and from the page so something is being stored.

    Emily

     

    Sunday, February 6, 2011 9:54 PM
  • The code I posted above is different than what you originally tried because it doesn't run until after the listbox is created and the items are filled in.
    Monday, February 7, 2011 2:37 PM
    Moderator