我在这里和网上都做了一些搜索,但要么我使用了错误的关键字,要么MVVM上的大部分例子都只处理一个模型。
我的项目中有两个模型(MVVM上的自学项目),歌曲模型和艺术家模型。到目前为止,能够将listview与一组信息(来自歌曲)绑定在一起,这样当用户点击listview上的一行时,就会在少数文本框控件中填充有关歌曲的信息。
我面临的问题是如何在两个模型之间进行通信?如果我们将模型视为具有列/字段的表格,那么我应该能够创建对艺术家模型(外键)的引用,但我没有得到的是当我cilck时如何检索有关艺术家的信息在列表视图中他的歌?
长话短说,我喜欢点击列表视图中的一行,显示歌曲列表,然后获取其歌手/艺术家图片,他的真实姓名等。我不遵循如何找到相关部分背后的概念有关艺术家模型中歌曲的数据。
任何建议都会被推荐。
这就是我现在所拥有的:
public class Song
{
string _singerId;
string _singerName;
string _songName;
string _songWriter;
string _genre;
int _songYear;
Artist artistReference;
然后我有:
public class Artist
{
string _artistBirthName;
string _artistNationality;
string _artistImageFile;
DateTime _artistDateOfBirth;
DateTime _artistDateOfDeath;
bool _isArtistAlive;
感谢。
编辑:
以下是我提供信息的方式:
问题是如何在歌曲集中插入艺术家参考?
Artists = new ObservableCollection<Artist>()
{
new Artist() { ArtistBirthName = "Francis Albert Sinatra", ArtistNickName = "Ol' Blue Eyes", ArtistNationality = "American", ... },
new Artist() { ArtistBirthName = "Elvis Aaron Presley", ArtistNickName = "", ArtistNationality = "American", ... },
new Artist() { ArtistBirthName = "James Paul McCartney", ArtistNickName = "", ArtistNationality = "British", ... },
new Artist() { ArtistBirthName = "Thomas John Woodward", ArtistNickName = "", ArtistNationality = "British", ... }
};
//later read it from xml file or a table.
Songs = new ObservableCollection<Song>()
{
new Song() {ARTIST INFO GOES HERE? HOW?, SingerName = "Fank Sinatra", SongName="Fly me to the Moon", SongWriterName="Bart Howard", Genre="Jazz" ,YearOfRelease= 1980 },
new Song() {SingerName = "Elvis Presley", SongName="Can't Help Falling in Love", SongWriterName="Paul Anka", Genre="Pop", YearOfRelease= 1969},
new Song() {SingerName = "The Beatles", SongName="Let It Be", SongWriterName="John Lennon", Genre="Rock", YearOfRelease= 1970},
new Song() {SingerName = "Tom Jones", SongName="Its Not Unusual", SongWriterName="Les Reed & Gordon Mills", Genre="Pop" , YearOfRelease= 1965}
};
答案 0 :(得分:1)
我要么在这里遗漏了一些东西,要么就是在寻找困难的地方。 :)创建歌曲对象时,只需将艺术家传递给它即可。例如Artist artist1 = new Artist(...); Song song1 = new Song(..., artist1);
您当然希望首先定义构造函数。
编辑:编辑后:)
您可以这样做:
using System.Linq; // For lambda operations
(...)
Songs = new ObservableCollection<Song>()
{
new Song() {Artist = Artists.FirstOrDefault(x => x.Name == "Francis Albert Sinatra"), SingerName = ...}
(...)
}
Artists.FirstOrDefault(...)
部分是LINQ查询。它遍历Artists
集合并选择集合中与条件匹配的第一个项目。如果找不到匹配项,则使用默认值,该值应为NULL。最好给每个艺术家一个唯一的ID,然后通过它而不是名字进行搜索,因为可以有更多具有相同名称的艺术家。如果您有更多问题,请随时询问!