猿问

C# WPF 与深层/子对象路径绑定

我有一个看起来像这样的 WPF 控件:


<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>

幕后代码如下所示:


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";

    }

  }

}

基于我一直在阅读的各种教程和文章,我的期望是绑定会找到用户控件上的 DataContext 属性,然后从那里查看路径并跟踪子对象,以便值在 MyControl.DataContext.Contact.Address 中找到将显示在 MyControl.txtContactAddress 中。


显然,这不会发生,如果我只是将 Path 设为单个属性,我 - 可以 - 让它工作:


<TextBox x:Name="txtContactAddress" Text="{Binding Path=Address}">

...然后将 DataContext 直接设置为 DataBindings.Contact 子对象:


    public MyControl()

    {

      InitializeComponent();

      this.DataContext = Data.Contact;

    }

然而,这打破了对本组织的约束。我是否只是缺少 Path 元素上的一些基本语法?


编辑:这不是以下内容的重复: 为什么 WPF 支持绑定到对象的属性,但不支持绑定到字段?


这个答案可能会解决这个问题,但它假设用户已经知道 field-vs-property 是根本原因。换句话说,当我开始时,我不会知道问题在于我使用了字段,所以我不会找到其他答案。然而,这个问题正在努力确定根本原因和其他答案的线索。我建议不要将此标记为重复。


POPMUISE
浏览 299回答 1
1回答

慕运维8079593

没关系,您只是错过了 get 和 set 属性访问器:&nbsp;public class DataBindings&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public ContactData Contact { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public OrganizationData Organization { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public OtherData Other { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public DataBindings()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Organization = new OrganizationData();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Organization.Address = "123 Test Street";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Contact = new ContactData();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Contact.Address = "456 Test Street";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
随时随地看视频慕课网APP
我要回答