In a nutshell, I want to use DataContext binding to assign a label the value of a public automatic property in another class.
So I have a class containing a public automatic property like so:
public class MyData
{
public string DogName { get; set; }
}
My WPF form looks like this:

The CodeBehind for my WPF form is as so:
public partial class MainWindow : Window
{
private MyData myData;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
myData = new MyData();
myData.DogName = "Lulu";
label1.DataContext = myData.DogName;
}
}
This isn’t, however, changing the value of label1 to “Lulu”, it just stays at “Label”. What have I missed out?
Thanks
That is not exactly the common way to work with DataContexts (as you show it,
MyDataas a class serves no purpose at all).Try this instead:
now, you could for instance also use MyData to contain the label’s Width or so.
Another (probably most used) way is to set the parent’s DataContext, and make the individual elements use it’s properties: