Search code examples
c#wpfdatatemplateitemscontrolitemtemplate

WPF: Simplest ItemsControl will not display any items


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?


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}}" >