2008-09-12 56 views
1

有沒有辦法在列表框中獲取選定項的ItemContaner?在Silverlight 2.0 Beta 1中,我可以,但容器隱藏在Silverlight 2.0的Beta 2中。數據綁定時獲取列表框的ItemContainer

我試圖調整列表框項目的大小,當它被取消選定到一個特定的大小和選擇一個可變大小。我也想獲取所選動畫項目的相對位置。增長到一個可變的大小,並獲得相關的分數是爲什麼我需要到列表框項目。

我應該澄清我不明確地將項目添加到列表框。我在xaml和DataTemplates中使用數據綁定。我無法訪問的是所選項目的DataTemplate的ItemContainer。

+0

你可以使用反射來做到這一點,但是如果它們被隱藏了,它可能是因爲直接改變它可能會導致列表框狀態變得不穩定。雖然MS控制無聊,但它們非常可靠。與他們的受保護和私人成員混淆可能會使他們變得不穩定,這不是一個好主意。如果你描述你在做什麼,可能會有更好的方式去做它... – Will 2008-09-12 18:38:02

回答

0

如果您將非UI元素添加到列表框(例如字符串或非UI數據對象),那麼這可能相當困難。但是,如果在將項目添加到列表框之前將其包裝在某種FrameworkElement派生對象中,則可以使用TransformToVisual獲取相對大小並使用「高度」和「寬度」來設置項目的大小。

一般而言,您可以將對象封裝在ContentControl中,如下所示。相反的:當你_ListBox.SelectedItem你可以將它轉換爲ContentControl中,並設置規模和獲得的相對位置

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

現在:

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

執行此操作。如果您需要原始對象,只需獲取該項目的Content屬性的值即可。

2

有一種方法可以獲取包含項目的UIElement和項目映射到UIElements的面板。你必須從Control繼承(這實際上適用於任何的ItemsControl),並覆蓋PrepareContainerForItemOverride:

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

這是種hackish的,但它工作得很好。

0

看來您可以使用相對綁定從ItemTemplate獲取Item容器。

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

我發現這個解決方案here。現在支持

0

更新爲Silverlight 5

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

的RelativeSource AncestorType,使這個容易得多。