2016-02-26 114 views
1

內一個ObservableCollection我有綁定到ObservableCollectionItemsControl。裏面那個ItemsControl我有另一ItemsControl這勢必會包含在最外層ItemsControl的的ObservableCollection的對象內的另一個ObservableCollection。當XAML解析器試圖建立最裏面ItemsControlDataTemplate有拋出的異常如何綁定嵌套的ItemsControl的ItemsSource嵌套母ItemControl的綁定項

System.Windows.Markup.XamlParseException:增加值 類型的集合‘System.Windows.Controls.ItemCollection’拋出例外。

和內部異常是:

System.InvalidOperationException:操作是無效的,而 的ItemsSource正在使用中。使用 而不是使用ItemsControl.ItemsSource訪問和修改元素。

爲了讓更多一點清楚,這是我的XAML結構:

<Grid DataContext="{Binding ...Name of object holding ObservableCollection here}"> 
     <ItemsControl Name="FilterItemsHolder" Grid.Row="1" 
        HorizontalAlignment="Stretch" VerticalAlignment="Top" 
        Margin="10,10,10,10" MinWidth="200" 
        Background="#151515" 
        ItemsSource="{Binding CheckedFilterColumns}" > 
      <ItemsControl.ItemTemplate> 
       <DataTemplate> 
        <Grid MaxHeight="100"> 
         <ItemsControl Name="FilterSelectionsHolder" 
            HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
            Margin="10,10,10,10" MaxHeight="50" 
            ItemsSource="{Binding FilterSelections}"> 
          <DataTemplate> 
           <rb:RBFilterOptions x:Name="FilterOptions" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" /> 
          </DataTemplate> 
         </ItemsControl> 
        </Grid> 
       </DataTemplate> 
      </ItemsControl.ItemTemplate> 
     </ItemsControl> 
    </Grid> 

數據綁定項目的階級結構是:

public class ClassThatHoldsCollections... 
{ 
    ... some other properties 
    public ObservableCollection<RBDataColumn> CheckedFilterColumns { get; set; } //bound to outermost ItemsControl's (Name="FilterItemsHolder") ItemsSource 

    public ClassThatHoldsCollections...() 
    { 
     ...initialize property values... 
     CheckedFilterColumns = new ObservableCollection<RBDataColumn>(); 
    } 
} 
public class RBDataColumn 
{ 
    ...some properties 

    public ObservableCollection<RBDataColumnFilterSelection> FilterSelections { get; set; } //bound to innermost ItemsControl's (Name="FilterSelectionsHolder") ItemsSource 

    public RBDataColumn() 
    { 
     ...initialize property values... 
     FilterSelections = new ObservableCollection<RBDataColumnFilterSelection>(); 
    } 
} 

奇怪的是,如果我註釋掉<DataTemplate>...</DataTemplate>不再拋出異常。如果我離開<DataTemplate></DataTemplate>標記並僅在<rb:RBFilterOptions.../>內註釋掉引用的用戶控件,則仍會拋出異常,這意味着它不能是導致此問題的基礎用戶控件。

在我看來,構建窗口的XAML分析器正試圖添加內部ItemsControl的值,同時仍然訪問最外面的ItemsControl's。

我的問題,分爲兩個部分,IS:

  1. 爲什麼拋出的異常?
  2. 是否有嵌套ItemsControl(胡)的ItemsSource屬性指出嵌套ObservableCollections的方法嗎?

回答

1

的線索是在錯誤信息,即有出錯了XAML。具體而言,您已經聲明自己內心DataTemplateFilterSelectionsHolder直接孩子,所以XAML分析器認爲你將其添加爲集合項目,而不是一個模板。嘗試將內部DataTemplate包裝在ItemsControl.ItemTemplate塊中。

有時只需第二組的眼睛。 ;)

+1

難以置信,我不敢相信我沒有注意到!感謝您的幫助,我確信這將解決問題。我一直在頭上撞牆。 – Kidiskidvogingogin