代码之家  ›  专栏  ›  技术社区  ›  Brian Leahy

数据绑定时获取Listbox的ItemContainer

  •  1
  • Brian Leahy  · 技术社区  · 16 年前

    有没有办法在列表框中获取所选项目的ItemContaner?在Silverlight2.0Beta1中我可以,但是容器隐藏在Silverlight2.0的beta2中。

    我试图调整列表框项的大小,当它被取消选择到一个特定的大小,当选择一个可变的大小。我还想得到动画所选项目的相对位置。增长到可变大小并获得相对大小是我需要访问listbox项的原因。

    我应该澄清我没有明确地向列表框中添加项。我在xaml和DataTemplates中使用数据绑定。我在访问所选项目的DataTemplate的ItemContainer时遇到问题。

    4 回复  |  直到 16 年前
        1
  •  2
  •   MaxM    16 年前

    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);
            var el = element as FrameworkElement;
            if (el != null)
            {
                // here is the elements's panel:
                _itemsHost = el.Parent as Panel;
    
                // item is original item inserted in Items or ItemsSource
                // we can save the mapping between items and FrameworElements:
                _elementMapping[item] = el;
            }
        }
    

    这有点老套,但效果很好。

        2
  •  0
  •   dcstraw    16 年前

    如果要向列表框添加非UI元素(例如字符串或非UI数据对象),那么这可能相当困难。但是,如果在将项添加到列表框之前将其包装在某种FrameworkElement派生对象中,则可以使用TransformToVisual获取相对大小,并使用Height和Width设置项的大小。

    一般来说,您可以像下面这样在ContentControl中包装对象。而不是:

    _ListBox.Items.Add(obj0);
    _ListBox.Items.Add(obj1);
    

    这样做:

    _ListBox.Items.Add(new ContentControl { Content = obj0 });
    _ListBox.Items.Add(new ContentControl { Content = obj1 });
    

        3
  •  0
  •   jpierson    15 年前

    <TextBlock YourTargetProperty="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ListBoxItem}}, Mode=OneWay, Path=YourSourceProperty}" />
    

    我找到了这个解决方案 here .

        4
  •  0
  •   Parrhesia Joe    13 年前

                  <ListBox ItemsSource="{Binding Properties}">
                     <ListBox.ItemTemplate>
                        <DataTemplate>
                           <TextBlock Text="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}}" />
                        </DataTemplate>
                     </ListBox.ItemTemplate>