In this article I explained how to use user control with datacontext which is defined in the code behind, now I will explain how to use datacontext without code behind.
User control XAML:
<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> <Label Content="{Binding myContent}"/> </Grid> </UserControl>
Then main window XAML:
<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>
Here notice line: <myUserControl:myControl DataContext="{Binding Source={StaticResource UserControlDataContextViewModel}}"/>
And view model looks like this:
public class UserControlDataContextViewModel { public string myContent { get; set; } public UserControlDataContextViewModel() { myContent = "test"; } }
Example project you can download from here.