I am attempting to get to grips with DataBinding, and I have just started to introduce UserControls into the mix, but it appears I cannot even get the most basic example working.
I have a MainWindow that contains a property (Subtitle) along with an instance of a UserControl. A property of the UserControl (LabelContent) is bound to the Subtitle property. The expected result is that changing the Subtitle property of MainWindow will update the LabelContent property of the UserControl, which is bound to the actual Content property of a Label within the UserControl:
I have MainWindow.xaml:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<local:UserControlSample LabelContent="{Binding Subtitle}"/>
With the following code behind (MainWindow.cs):
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
Subtitle = "Test";
}
public String Subtitle
{
get;
set;
}
}
UserControlSample.xaml:
<UserControl x:Class="WpfApp1.UserControlSample"
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"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Label Content="{Binding Path=LabelContent}"/>
UserControl.cs:
public partial class UserControlSample : UserControl
{
public static DependencyProperty LabelContentProperty = DependencyProperty.Register("LabelContent", typeof(String), typeof(UserControlSample));
public UserControlSample()
{
InitializeComponent();
DataContext = this;
}
public String LabelContent
{
get { return (String)GetValue(LabelContentProperty); }
set { SetValue(LabelContentProperty, value); }
}
}
I believe it is something to do with DataContexts however I do not understand them too well as yet. If I change UserControl to the following, then I achieve the expected results. However this does not explain the reasons why the original code fails:
UserControlSample.xaml
<Label Content="{Binding Path=Subtitle}"/>
UserControl.cs
public UserControlSample()
{
InitializeComponent();
}