I have a WPF control that looks like this:
<UserControl x:Class="MyApp.MyControl" ...etc...>
<StackPanel>
<Label Content="Contact Information" />
<TextBox x:Name="txtContactAddress" Text="{Binding Path=Contact.Address}">
<Label Content="Organization Information" />
<TextBox x:Name="txtOrgAddress" Text="{Binding Path=Organization.Address}">
</StackPanel>
</UserControl>
The code behind the scenes looks like:
namespace MyApp
{
public class MyControl : UserControl
{
public DataBindings Data = new DataBindings();
public MyControl()
{
InitializeComponent();
this.DataContext = Data;
}
}
public class DataBindings
{
public ContactData Contact;
public OrganizationData Organization;
public OtherData Other;
public DataBindings()
{
Organization = new OrganizationData();
Organization.Address = "123 Test Street";
Contact = new ContactData();
Contact.Address = "456 Test Street";
}
}
}
My expectation based on the various tutorials and articles I've been reading, is that the binding would find the DataContext property on the user control, then from there, it would look at the path and follow the sub-objects, so that the value found in MyControl.DataContext.Contact.Address would show up in MyControl.txtContactAddress.
Obviously, this is not happening, and I -CAN- get it to work if I just make the Path into a single property:
<TextBox x:Name="txtContactAddress" Text="{Binding Path=Address}">
...and then just set the DataContext directly to the DataBindings.Contact sub-object:
public MyControl()
{
InitializeComponent();
this.DataContext = Data.Contact;
}
However, this breaks the binding for the Organization. Am I just missing some basic syntax on the Path element?
EDIT: This is NOT a duplicate of: Why does WPF support binding to properties of an object, but not fields?
That answer might resolve this one, but it assumes that the user already knows that the field-vs-property is the root cause. In other words, when I started, I wouldn't have known that the problem was that I was using fields, so I wouldn't have found that other answer. This question, however, is working to establish root cause and LEADS to that other answer. I'd recommend not flagging this as a duplicate.