如何绑定另一个项目中的属性



我正在使用MVVM模式编写C#,WPF应用程序。我正在尝试绑定我编写的不同项目的属性。在运行应用程序时,显示的属性,但在运行时更新属性时,现在更新了属性。

重要的是要说 Proj1 中的名称正在更新

namespace Proj1
{
  public class Human: inotifypropertychanged
  {
     private string _name;
     public string Name{
                          get{ return _name;}
                          set{ _name = value;
                             OnPropertyChange("Name");}
                       }
     public Human()
     {
        Name = "Danny";
     }
     //implement correctly the inotifypropertychanged
  }
}
namespace Proj2WpfApp
{
  public class MainViewModel: inotifypropertychanged
  {
     private Human human;
     private string _humanName
     public string HumanName{
                          get{ return _humanName;}
                          set{ _humanName = human.Name;
                             OnPropertyChange("HumanName");}
                       }
     public MainViewModel()
     {
        human = new Human();
     }
  //updating the name
  }
}

在 XAML 代码中

<TextBlock Text ="{binding HumanName}"/>

设置 HumanName 属性的值不会神奇地更改human.Name 。设置HumanName时也不会更新human.Name

您应该将 MainViewModel 更改为具有 Human 属性而不是HumanName

public class MainViewModel: INotifyPropertyChanged
{
    private Human human;
    public Human Human
    {
        get { return human; }
        set
        {
            human = value;
            OnPropertyChange("Human");
        }
    }
    ...
}

然后像这样绑定:

<TextBlock Text ="{Binding Human.Name}"/>

最新更新