WPF:ItemsControl 和 DataContext

Den*_*gan 3 c# wpf datacontext itemscontrol

我有一个主窗口,其中有一个用户控件,称为SuperMode. SuperMode由一群人组成,这个集合中的每个人都有自己的任务集合。听起来很简单,对吧?

从文件SuperMode.xaml

<UserControl 
    x:Class="Prototype.SuperMode"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Prototype"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"> <!-- NOTE! -->
    <!-- Look at how I'm setting the DataContext, as I think it's
         important to solve the problem! -->

    <ScrollViewer CanContentScroll="True">
        <ItemsControl ItemsSource="{Binding People}" Margin="1">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <UniformGrid Rows="1"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </ScrollViewer>

</UserControl>
Run Code Online (Sandbox Code Playgroud)

这很好用,我可以像预期的那样看到个人!现在我所要做的就是为Person用户控件获取正确的 XAML,以便同时显示他们的所有任务。

如您所见,我正在使用该People属性用项目填充控件。该People属性具有 type ObservableCollection<Person>,其中Person另一个用户控件是这样的......

来自Person.xaml

<UserControl 
    x:Class="Prototype.Person"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Prototype">

    <Border Background="Black" CornerRadius="4" Margin="1">
        <ItemsControl ItemsSource="{Binding Tasks}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </Border>

</UserControl>
Run Code Online (Sandbox Code Playgroud)

Tasks这是Personwith 类型的属性ObservableCollection<Task>。这就是它卡住的地方!显然 WPF 找不到任何Tasks属性并查看 VS2008 的输出窗口,我发现以下内容:

System.Windows.Data 错误:39:BindingExpression 路径错误:在“对象”“超级模式”(名称 =“超级模式”)上找不到“任务”属性。BindingExpression:Path=Tasks; DataItem='SuperMode' (Name='SuperMode'); 目标元素是 'ItemsControl' (Name=''); 目标属性是“ItemsSource”(类型“IEnumerable”)

现在我迷路了。看来我必须DataContext在 each上设置属性Person,否则它仍然会认为数据上下文是SuperMode,但是我该怎么做呢?

Ken*_*art 5

忽略您所拥有的相当不愉快的设计(您应该查看 MVVM),您应该能够DataContext为 child UserControls设置如下:

<ItemsControl ItemsSource="{Binding People}" Margin="1">
    <ItemsControl.ItemContainerStyle>
        <Style>
            <Setter Property="FrameworkElement.DataContext" Value="{Binding RelativeSource={RelativeSource Self}}"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Rows="1"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)