-2

The code below shows the simplest example of data binding I can think of, and it works: With my DataContext set to this, and my Binding path in XAML to my string Name1, the app displays the expected 'Peter'. But if I change that path to Emp.Name1, a property in the instantiated class of Employee, I would expect the app to display 'Paul', but it displays nothing. Why is that? (I know I can set the DataContext to Emp and the Path to Name1 and that would work, but I'm trying to understand why a Path of Emp.Name1 with a DataContext of this doesn't work: don't I have access to all the properties in the object pointed to by this (MainWindow) and isn't Emp.Name1 a property in that object?)

<Window x:Class = "DataBindingOneWay.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   Height = "350" Width = "600">

    <StackPanel>
        <TextBlock Text="{Binding Path=Name1}" />
    </StackPanel>
 
</Window>
using System.Windows;

namespace DataBindingOneWay
{
    public partial class MainWindow : Window
    {
        public class Employee
        {
            public string? Name1 { get; set; } = "Paul";
        }

        public string? Name1 { get; set; } = "Peter";

        public Employee Emp;

        public MainWindow()
        {
            InitializeComponent();
            Emp = new Employee();
            // DataContext = Emp;
            DataContext = this;
        }
    }
}

1 Answers1

2

Declare Emp as a public property, not a field

public Employee Emp { set; get; }
Muhammad Sulaiman
  • 2,399
  • 4
  • 14
  • 28