0

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?

burhan
  • 121
  • 1
  • 9
  • why do you want to show only 1 item? you want to show **all the properties** of that item in the listbox (each property corresponds to 1 item)? – King King Dec 05 '13 at 00:55

1 Answers1

0

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.

Community
  • 1
  • 1
Noctis
  • 11,507
  • 3
  • 43
  • 82