WPF: ItemsControl and DataContext

I have a main window with one user control called SuperMode. SuperModeconsists of a collection of people, and each person in this collection has its own set of tasks. That sounds easy, right?

From file 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>

It works great, and I see four people as I expect! Now all I have to do is get the XAML for the user control Personin order to display all their tasks.

As you can see, I use the property Peopleto populate the control with the elements. The property Peopleis of type ObservableCollection<Person>where Personis another user control as such ...

From 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>

Tasks Person ObservableCollection<Task>. ! -, WPF - Tasks , VS2008, :

System.Windows.Data: 39: BindingExpression: "" "" '' SuperMode '(Name=' SuperMode ')'. BindingExpression: Path = ; DataItem = 'SuperMode' (Name= 'SuperMode'); - "ItemsControl" (Name= ''); target - "ItemsSource" ( "IEnumerable" )

. , DataContext Person, , SuperMode, ?

+3
1

( MVVM), DataContext UserControl :

<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>
+4

Source: https://habr.com/ru/post/1731883/


All Articles