以编程方式访问WPF控件

时间:2012-10-08 20:08:09

标签: c# wpf .net-4.5

这个问题可能很明显,但我很难看到它。

我有以下XAML:

<ItemsControl x:Name="contentList">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="200" />
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{Binding Name}" TextWrapping="Wrap" />
                    <ItemsControl x:Name="imageContent" Grid.Column="1">
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding ImageCollection.FullName}" TextWrapping="Wrap" />
                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                    </ItemsControl>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

我为contentList设置了itemsSource,如下所示:

contentList.ItemsSource = myObservableCollection;

但是,当我尝试对imageContent执行相同操作时,我似乎无法通过IntelliSense访问它。 我已经尝试了清理/重建项目,但没有任何区别。

我是否需要以不同的方式访问imageContent?

我想对contentList和imageContent使用myObservableCollection,因为它具有以下结构:

  • 名称(字符串)
  • ImageCollection(ObservableCollection)

旨在产生以下用户界面:

enter image description here

1 个答案:

答案 0 :(得分:2)

您需要在外部集合的列表对象中定义另一个ObservableCollection。像这样:

ObservableCollection<MyObject> OuterList = new ObservableCollection<MyObject>();

//...


public class MyObject
{
    public ObservableCollection<FileInfo> ImageCollection {get; set;}
    public MyObject()
    {
        ImageCollection = new ObservableCollection<FileInfo>();
    }
}

然后就像这样更新你的xaml:

...
<ItemsControl x:Name="imageContent" ItemsSource="{Binding ImageCollection}">
...

因此,这会导致外部列表中的每个项目都拥有它自己的可观察集合,并保存它的列表。

此外,通过此更改,请确保更新文本块上的绑定,因为每个项目都代表一个FileInfo对象,您可以简单地写一下:

<DataTemplate>
    <TextBlock Text="{Binding FullName}" TextWrapping="Wrap" />
</DataTemplate>