Now idea is to have one control inside ItemsControl, and everything that inside UserControl, something like:
<UserControl x:Class="MyUserControl.myControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <Grid> <ItemsControl ItemsSource="{Binding myLabels}"> <ItemsControl.ItemTemplate> <DataTemplate> <Label Content="{Binding DataContext.myContent, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Grid> </UserControl>
Here notice line:
<Label Content="{Binding DataContext.myContent, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"/>
This line was taken from here.
My MainWindow.xaml looks like this:
<Window x:Class="UserControlDataContext.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:myUserControl="clr-namespace:MyUserControl;assembly=MyUserControl" xmlns:viewModel="clr-namespace:UserControlDataContext.ViewModel" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.Resources> <viewModel:UserControlDataContextViewModel x:Key="UserControlDataContextViewModel" /> </Grid.Resources> <myUserControl:myControl DataContext="{Binding Source={StaticResource UserControlDataContextViewModel}}"/> </Grid> </Window>
and view model like:
public class UserControlDataContextViewModel { public string myContent { get; set; } public IEnumerable<string> myLabels { get; set; } public UserControlDataContextViewModel() { myContent = "test"; myLabels = new[] { "test1", "test2" }; } }
Example project you can download from here.