0

I'm having difficulties to Binding a ListView inside of a TabControl Bellow is my ViewModel

public ObservableCollection<TabItem> Tabs { get; set; }
public class TabItem
{
    public string Header { get; set; }
    public ObservableCollection<abc> Content { get; set; }
}
public class abc
{
    public string text { get; set; }
}

this is how I initialize it

InitializeComponent();
Tabs = new ObservableCollection<TabItem>()
{
    new TabItem {
        Header = "Header1",
        Content = new ObservableCollection<abc>()
        {
            new abc{ text = "content1" },
            new abc{ text = "content2" },
        }
    },
    new TabItem {
        Header = "Header2",
        Content = new ObservableCollection<abc>()
        {
            new abc{ text = "content3" },
            new abc{ text = "content4" },
        }
    }
};
tabControl1.ItemsSource = Tabs;

and here is how I populate and Bind it in the view

<TabControl Name="tabControl1">
    <TabControl.ItemTemplate>
        <!-- this is the header template-->
        <DataTemplate>
            <TextBlock Width="500" Text="{Binding Header}" />
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <!-- this is the body of the TabItem template-->
        <DataTemplate>
            <ListView Margin="10" ItemsSource="{Binding Content}">
                <ListViewItem>
                    <StackPanel>
                        <TextBlock Text="{Binding text}" />
                    </StackPanel>
                </ListViewItem>
            </ListView>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

but then I got an errror saying that

InvalidOperationException: Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.

How can I bind a ListView inside a TabControl? Each Tab control will have the same format of ListView. The Actual ListView will have more than 1 field. not only text field.

Where did I do it wrongly?

Mark
  • 2,041
  • 2
  • 18
  • 35

1 Answers1

1

ListViewItems are created by ListView for each element in ItemsSource. To change their look you need ItemTemplate:

<ListView Margin="10" ItemsSource="{Binding Content}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding text}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

if you have more than 1 field, not only text field, define GridView with columns like shown in this post

ASh
  • 34,632
  • 9
  • 60
  • 82
  • thx for the explanation. I always thought my problem was with the `Binding`. It turns out that the problem was with `ItemTemplate`. since each `ListView` would still be designed into a box, so im planing to use `Grid` inside the `DataTemplate`. thank you – Mark Mar 18 '21 at 08:11