【问题标题】:How do I bind a property from another project [closed]如何绑定来自另一个项目的属性[关闭]
【发布时间】:2023-04-08 11:19:01
【问题描述】:

我正在使用 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}"/>

【问题讨论】:

  • 你想在 MainViewModel 中使用人类的 Name-Property 吗?我不明白 MainViewModel 和 Human 类之间的关系。他们都只实现了一个名为 Name 的属性

标签: c# wpf mvvm


【解决方案1】:

当您设置human.Name 时,HumanName 属性的值不会神奇地改变。当您设置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}"/>

【讨论】:

  • 我也宁愿使用这种组合方式...
猜你喜欢
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多