Question

I can't get the simplest idea of an ItemControl to work. I just want to populate my ItemsControl with a bunch of SomeItem.

This is the code-behind:

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

namespace Hax
{

    public partial class MainWindow : Window
    {

        public class SomeItem
        {
            public string Text { get; set; }
            public SomeItem(string text)
            {
                Text = text;
            }
        }

        public ObservableCollection<SomeItem> Participants
            { get { return m_Participants; } set { m_Participants = value; } }
        private ObservableCollection<SomeItem> m_Participants
            = new ObservableCollection<SomeItem>();

        public MainWindow()
        {
            InitializeComponent();
            Participants.Add(new SomeItem("Hej!"));
            Participants.Add(new SomeItem("Tjenare"));
        }
    }
}

This is the XAML:

<ItemsControl Name="itemsParticipants"
    ItemsSource="{Binding Path=Participants}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="Red" BorderThickness="2">
                <TextBlock Text="{Binding Text}" />
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

What am I doing wrong?

Was it helpful?

Solution

Make sure your datacontext is set to RelativeSource Self somewhere in your xaml. If you could post more of your xaml it might be helpful.

<ItemsControl... DataContext="{Binding RelativeSource={RelativeSource Self}}" >

OTHER TIPS

The ItemsSource references a property called MyParticipants, whereas the code it looks to be Participants.

Check the Debug Output view, and you should see error messages.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top