【问题标题】:Listbox fails to show all of its items' content列表框无法显示其所有项目的内容
【发布时间】:2012-01-27 11:38:12
【问题描述】:

我正在开发一个 C#/WPF 程序并创建了一个包含两个文本框(和一个网格)的用户控件。

我的主窗口中有一个列表框。它的项目源设置为我的mentionend 用户控件的集合。当我填充它并调试程序时,它包含 20 个项目,并且所有项目中都有我想要的文本。但是在加载主窗口(并填充列表框)后,它会显示所有项目,但其中只有九个具有带文本的文本框。其他的有没有任何文本的文本框。

这可能是什么原因?

更新:这里是代码。

用户控件:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="40" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <TextBox x:Name="NumberColumn" x:FieldModifier="public" Text="{Binding LineNumber}"
             Grid.Column="0" HorizontalAlignment="Right" />
    <TextBox x:Name="TextColumn" x:FieldModifier="public" Text="{Binding Text}"
             Grid.Column="1" HorizontalAlignment="Left" />            
</Grid>

列表框的填充:

string line;
Collection<CustomLine> lines = new Collection<CustomLine>();
StreamReader reader = new StreamReader(@"2008.sln");
while ((line = reader.ReadLine()) != null)
{
    CustomLine myLine = new CustomLine(line, lines.Count + 1);
    lines.Add(myLine);
}

this.leftListBox.ItemsSource = lines;

列表框的 XAML:

<ListBox x:Name="leftListBox" Grid.Column="0" Margin="10"
             MouseDown="leftListBox_MouseDown" SelectionChanged="leftListBox_SelectionChanged">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <UserControl>
                    <local:CustomLine />
                </UserControl>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

如果可能有另一段代码正在使用,我也可以稍后添加。

【问题讨论】:

  • 原因很可能是您的某些代码。如果您分享它,答案可能会变得更加具体。
  • 我也想过这个问题。但我不确定我应该在这里粘贴哪些代码。我已经更新了原帖。

标签: c# wpf user-controls listbox itemssource


【解决方案1】:

为什么将CustomLine 控件包装在UserControl 标记中?

我最好的猜测是UserControl 告诉ListBox 这些项目的大小不正确,因此ListBox 只加载它认为可见的项目。这是因为 ListBox 的默认行为是使用 UI 虚拟化,因此它只呈现可见的控件,滚动 ListBox 将重用现有控件并替换它们后面的 DataContext 而不是创建新控件。

尝试删除ItemTemplate 中的UserControl

<ListBox.ItemTemplate>
    <DataTemplate>
        <local:CustomLine />
    </DataTemplate>
</ListBox.ItemTemplate>

【讨论】:

  • 谢谢,这就是重点!我使用了UserControl 标签,因为我是这样学习的——显然是错误的。也谢谢你的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多