-3

I have a problem with binding ObservableCollections. Other properties (string) are OK. Here is my code:

MainWindow.xaml

<StackPanel>
    <TextBlock Text="{Binding Title}"/>
    <ItemsControl ItemsSource="{Binding Data}">
        <TextBlock Text="{Binding B}"/>
    </ItemsControl>
</StackPanel>

MainWindow.xaml.cs

public MainWindow()
{
   InitializeComponent();
   DataContext = new MainWindowVm();
}

MainWindowVm

class MainWindowVm
{
    public ObservableCollection<A> Data;
    public string Title { get; set; } = "HELLO WORLD";
    public MainWindowVm()
    {
        Data = new ObservableCollection<A>() {new A() {B = "X"}, new A() {B = "X"}};
    }
}

class A
{
    public string B { get; set; }
}

Result enter image description here

What am I doing wrong?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
bluray
  • 1,875
  • 5
  • 36
  • 68

1 Answers1

3

OK, as others already mentioned, you need to change the Data field into a property.

public ObservableCollection<A> Data { get; set; }

To get rid of the error

Items collection must be empty before using ItemsSource.

Change your XAML to:

 <StackPanel>
    <TextBlock Text="{Binding Title}"/>
    <ItemsControl ItemsSource="{Binding Data}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding B}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</StackPanel>
ChristianMurschall
  • 1,621
  • 15
  • 26