How will i show the first item of an observablecollection in a Listbox?

1.7k views Asked by At

i have this declaration:

    public ObservableCollection<SomeType> Collection { get; set; }

i tried something, like:

    myListBox.ItemsSource = Collection[0];

to show the first item of Collection in the Listbox control, but it gives error.

how will i do this? what change should i make on the right side?

1

There are 1 answers

3
Noctis On

You need to bind the ItemSource to your collection, and then set the selected index to the one you want (0 in your case)

Here's the smallest example. XAML:

<Window x:Class="WPFSOTETS.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
        <ComboBox ItemsSource="{Binding Collection}" SelectedIndex="2"></ComboBox>
    </Grid>
</Window>

Code behind:

using System.Collections.ObjectModel;
using System.Windows;

namespace WPFSOTETS
{

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public ObservableCollection<string> Collection
        {
            get
            {
                return new ObservableCollection<string> {"one","two","three"};
            }
        }
    }
}

I set the index to 2, just for fun, but you can play with it.


As of comment, if you want to set this in the codebehind, you'll have to name your control, and then you can use it from your codebehind and do your binding and setting there. You can have a look at this answer for example.