我的问题是我想看到我的艺术家组合框在我的专辑组合框中选择了艺术家相关的专辑。
我在这个网站上找到了代码示例,它与我的问题类似:
但我不明白我们如何获得SelectedArtist值。我插入了这段代码并对其进行了测试,它一直给我null ...我试图从我所拥有的Artits列表中将artistName分配给SelectedArtist,但这并不成功:
在检查是否为null之前,有人可以帮助我找到SelectedArtist值吗
我目前有一个ComboBox,其中填充了艺术家名称,我需要在选择艺术家后将其绑定到另一个专辑的组合框。
在我看来,这些设置如下: XAML
<ComboBox Height="23" HorizontalAlignment="Left" Margin="65,81,0,0" Name="comboBox1" ItemsSource="{Binding Artists}" SelectedItem="{Binding SelectedArtist}" VerticalAlignment="Top" Width="120" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="65,115,0,0" Name="comboBox2" VerticalAlignment="Top" ItemsSource="{Binding Albums}" SelectedItem="{Binding SelectedAlbums}" Width="120" />
private void initialiseArtists()
{
MusicDataClassesDataContext dataClasses = new MusicDataClassesDataContext();
artistList = (from m in dataClasses.tblArtists select m.ArtistName).ToList();
}
public List<String> Artists
{
get
{
return this.artistList;
}
}
public List<String> Albums
{
set
{
initialiseAlbums();
}
get
{
return this.albumList;
}
}
public string SelectedArtist
{
set
{
this.selectedArtist = value;
initialiseAlbums();
}
}
private void initialiseAlbums()
{
if (selectedArtist != null)
{
MusicDataClassesDataContext dataClasses = new MusicDataClassesDataContext();
var getArtist = dataClasses.tblArtists.FirstOrDefault(band => band.ArtistName== selectedArtist);
albumList = (from album in dataClasses.tblAlbums
where album.ArtistID == getArtist.ArtistID
select album.AlbumName).ToList();
OnPropertyChanged("Albums");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));}
答案 0 :(得分:1)
我会做以下事情:
private List<string> _artists;
public List<string> Artists
{
get { return _artists; }
set
{
_artists = value;
OnPropertyChanged("Artists");
}
}
public List<string> Albums
{
get { return GetAllAlbumsByArtist(SelectedArtist); }
}
private string _selectedArtist;
public string SelectedArtist
{
get { return _selectedArtist; }
set
{
_selectedArtist= value;
OnPropertyChanged("SelectedArtist");
OnPropertyChanged("Albums");
}
}
public List<string> GetAllAlbumsByArtist(string artist)
{
//Write your code to get the album data.
}
然后,您在xaml中唯一要做的就是正确绑定两个组合框的ItensSource属性,并将UpdateSourceTrigger设置为&#34; PropertyChanged&#34;。
答案 1 :(得分:0)