简体   繁体   中英

How to bind a single view to multiple ViewModels properly?

I have a view which has bindings like:

<TextBlock Text="{Binding Attribute1, Mode=TwoWay}" />
<TextBlock Text="{Binding Attribute2, Mode=TwoWay}" />

Also I have tons of view models where dependency properties are called somehow ( Name , OfficialName , etc), but essentially they are Attribute1 , so I want to use the same view to show them to a user. All the bindings should be two-way. I was thinking about creating a temporary class like:

public class AttributesInfo
{
   string Attribute1{ get; set; }
   // other attributes
}

and expose in every view model a property Attributes :

return new AttributesInfo{ Attribute1 = Name, ... };
return new AttributesInfo{ Attribute1 = OfficialName, ... };

which would supply a view:

<TextBlock Text="{Binding AttributesInfo.Attribute1, Mode=TwoWay}" />

Now I am thinking about two-way bindings and I understood that this is a wrong solution. Is there any good one?

Better would be if you create an Interface with the required attribute properties and implement it in different VMs.

eg

public interface IAttribute
{
   string Attribute1 {get; set;}
   .
   .
   .
}

public class someVM : IAttribute
{
  private string _name;
  public string Nam
  {
     get {return _name;}
     set
     {
        _name = value;
        NotifyPropertyChanged("Name");
                 }
  }

  public string Attribute1
  {
     get{return this.Name;}
     set
     {
        this.Name = value; 
        NotifyPropertyChange("Attribute1");
     }
  }
}

In this way your properties will be in sync with the attributes and you can use same view for all VMs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM