【问题标题】:wpf - listview inside of tabcontrolwpf - 选项卡控件内的列表视图
【发布时间】:2021-03-18 07:46:30
【问题描述】:

我在Binding ListView TabControl 内遇到困难 Bellow 是我的 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; }
}

这就是我初始化它的方式

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;

这是我在视图中填充和Bind 的方式

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

然后我得到一个错误的说法

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

如何在TabControl 中绑定ListView? 每个选项卡控件都将具有相同的ListView 格式。实际的 ListView 将有超过 1 个字段。不仅是text 字段。

我哪里做错了?

【问题讨论】:

    标签: c# wpf listview tabcontrol


    【解决方案1】:

    ListViewItems 由 ListView 为 ItemsSource 中的每个元素创建。要改变它们的外观,您需要 ItemTemplate:

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

    如果您有多个字段,而不仅仅是文本字段,请使用 shown in this post 等列定义 GridView

    【讨论】:

    • 感谢您的解释。我一直认为我的问题出在Binding 上。原来问题出在ItemTemplate。因为每个ListView 仍然会被设计成一个盒子,所以我打算在DataTemplate 中使用Grid。谢谢
    猜你喜欢
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    相关资源
    最近更新 更多