2012-04-05 57 views
1

這不工作對我來說:綁定到UserControl元素的ListBox?

<StackPanel> 
    <ListBox x:Name="MyListBox" 
     ItemsSource="{StaticResource UserControlsCollection}"> 
     <ListBox.ItemsPanel> 
      <ItemsPanelTemplate> 
       <StackPanel Orientation="Horizontal" /> 
      </ItemsPanelTemplate> 
     </ListBox.ItemsPanel> 
    </ListBox> 
    <UserControl 
     Content="{Binding ElementName=MyListBox, Path=SelectedValue}" 
     /> 
</StackPanel> 

我得到這個在運行時「項目不在預期範圍內」的錯誤。這些數據:

<toolkit:ObjectCollection x:Key="UserControlsCollection"> 
    <UserControl Style="{StaticResource UserControlListItemStyle}"> 
     <Button>One Button</Button> 
    </UserControl> 
    <UserControl Style="{StaticResource UserControlListItemStyle}"> 
     <ComboBox> 
      <ComboBoxItem Content="One" IsSelected="True" /> 
      <ComboBoxItem Content="Two" /> 
      <ComboBoxItem Content="Three" /> 
     </ComboBox> 
    </UserControl> 
    <UserControl Style="{StaticResource UserControlListItemStyle}"> 
     <Rectangle 
      Fill="Red" 
      Width="120" Height="120" 
      /> 
    </UserControl> 
</toolkit:ObjectCollection> 
+0

我用Silverlight 4和4月份的Silverlight Toolkit測試了它,它工作正常。但是,我沒有你的風格「UserControlListItemStyle」。你使用的是什麼版本,你的風格是什麼樣的? – 2012-04-05 08:12:15

+0

編輯最後評論:選擇一個項目時發生錯誤。在那種情況下,我也會遇到錯誤。我會更多地考慮它。 – 2012-04-05 08:21:13

回答

0

您試圖顯示相同FrameworkElements(那些集合中)兩次:一次是在ListBox中的項目,選擇後綁定用戶控件第二次。

所有FrameworkElements只能在可視樹中掛鉤一次(即它們觸發加載的事件時)。

要實現你想要做的事情,你需要分開模型和視圖。模型將在您的集合中,可以是任何類型,通常實現INotifyPropertyChanged或從DependencyObject派生,並且您的視圖可以是DataTemplates作爲資源,其中Target屬性是模型的類型。

由於SL5,任何ContentControl與模型作爲其內容(同樣ListBox與模型作爲綁定集合的元素)將自動選取這些DataTemplates(如果它們在範圍內)。然後模板將被潛在地實例化多次,每個模型。