![](/img/trans.png)
[英]How to bind to the active ItemsControl item from a NESTED ItemsControl
[英]How to bind nested ItemsControl ItemsSource to an ObservableCollection nested within parent ItemControl's bound item
我有一个绑定到ObservableCollection
的ItemsControl
。 这里面的ItemsControl
我有另一个ItemsControl
被绑定到另一个ObservableCollection
包含最外侧的对象中ItemsControl
的的ObservableCollection。 当XAML解析器尝试构建最内部的ItemsControl
的DataTemplate
,将引发异常
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>
DataBound项的类结构为:
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
的值。
我的问题分为两个部分:
ItemsControl
(胡)的ItemsSource
属性指出嵌套ObservableCollections
? 提示是在错误消息中,即您的XAML出了点问题。 具体来说,您已将内部DataTemplate
声明为FilterSelectionsHolder
的直接子级,因此XAML解析器认为您将其添加为集合项而不是模板。 尝试将内部DataTemplate
包装在ItemsControl.ItemTemplate
块中。
有时只需要第二眼。 ;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.