开发者

WPF many-many binding between listviews

I have two listviews, one for Images and one for Tags, which have a many-many relationship.

Both listviews a开发者_StackOverflow中文版re bound to ObservableCollection of EF objects. The Tag listview also has a checkbox column.

When I select an Image from the listview I'd like the associated Tags to be checked on the other listview. I need TwoWay binding to create and remove the relationships based on being checked or not.

How can I do this?


in your VM you have two ObservableCollection of all Images and Tags... I think you can use two others ObservableCollection of associated Images or Tags, when you select an Image you can bind the associated Tags with this ObservableCollection and vise versa.

Other solution you can bind the associated items with selected item ("SelectedItems={Binding Path=SelectedItem.Tags, ElementName=MyImageListBox}", or something like that).


I've got this working as follows:

  • I have extended my Tag model to have an MatchesImage boolean property
  • I have bound the checkbox in my listviewitem twoway to this property
  • The getter gets the CurrentImage and returns CurrentImage.Tags.Contains(this)
  • When I change the checkbox in the property setter I retrieve the CurrentImage from my viewmodel (my viewmodels are global resources) and add/remove the Tag from it's Tags collection based on value
  • I will probably change CurrentImage to be accessible via a data repository, instead of the viewmodel

Something along the lines of:

public partial class Tag : INotifyPropertyChanged

  public bool MatchesImage {
    get
    {
        Image img = DataRepository.CurrentImage;
        return (img != null) ? this.Images.Contains(img) : false;
    }
    set
    {
        Image img = DataRepository.CurrentImage;
        if (img != null)
        {
            if (value)
                img.Tags.Add(this);
            else
                img.Tags.Remove(this);
            OnPropertyChanged("MatchesImage");
        }
    }
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜