简体   繁体   中英

wpf - listview inside of tabcontrol

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM