【问题标题】:ComboBox + VirtualizingStackPanel width bug?ComboBox + VirtualizingStackPanel 宽度错误?
【发布时间】:2016-12-05 05:57:47
【问题描述】:

在使用 ComboBox 和 VirtualizingStackPanel 时,我们的 Silverlight 应用程序遇到问题。当 ComboBox 项的宽度比控件本身宽得多并且该项仅在滚动后可见(即在加载时不可见)时,就会出现问题。拥有相当长的项目列表,ComboBox 滚动变得疯狂。

在谷歌上搜索一下,我只能看到一条评论描述了我们正在经历的事情,但没有找到解决方案。这似乎是一个错误,但也许我们要么做错了什么,要么有解决办法。标记很简单,大致如下所示

<ComboBox>
  <ComboBox.ItemsPanel>
    <ItemsPanelTemplate>
      <VirtualizingStackPanel />
    </ItemsPanelTemplate>
  </ComboBox.ItemsPanel>
</ComboBox>

顺便说一下,ComboBoxItems 是简单的文本。没有图形或其他对象。

【问题讨论】:

    标签: silverlight combobox silverlight-5.0


    【解决方案1】:

    我遇到了同样的问题,最终需要为组合框定义一个项目模板,并强制项目的宽度与外部列宽的宽度相匹配。这会使文本换行成多行,但您可以将其更改为使用 TextTrimming="WordEllipsis" 来修剪文本项。

    <Grid>
      <Grid.ColumnDefinitions>
        ...
        <ColumnDefinition Width="..." x:Name="cbColumn" />
      </Grid.ColumnDefinitions>
      <ComboBox>
        <ComboBox.ItemsPanel>
          <ItemsPanelTemplate>
            <VirtualizingStackPanel />
          </ItemsPanelTemplate>
        </ComboBox.ItemsPanel>
        <ComboBox.ItemTemplate>
          <DataTemplate>
            <TextBlock TextWrapping="Wrap" Width="{Binding ActualWidth, ElementName=cbColumn}" />
          </DataTemplate>
        </ComboBox.ItemTemplate>
      </ComboBox>
    </Grid>
    

    就我而言,我并不总是知道组合框需要多大的尺寸,所以这就是我使用绑定到网格列的原因。如果您知道想要组合框的大小,直接在项目模板中设置宽度可能同样有效。

    【讨论】:

    • 顺便说一句,有些人发现 TextWrap 和 WordEllipsis 不可接受。作为替代解决方案,我创建了一个派生自 ComboBox 的类并覆盖了 GetContainerForItemOverride() 方法。从那里我可以访问 ItemCollection 并能够根据“最宽”的项目确定要使用的最佳宽度。然后我设置调用 base.GetContainerForItemOverride() 获得的 ComboBoxItem,然后将 ComboxItem.Width 设置为确定的值。所以,基本上,所有的 ComboBoxItems 都具有相同的宽度,这可以防止 ScrollViewer 变得疯狂。
    猜你喜欢
    • 1970-01-01
    • 2021-12-15
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多