0

我的问题是我想在我的专辑组合框中看到我的艺术家组合框选择的艺术家相关专辑。

我在这个网站上找到了代码示例,它与我的问题类似:

但我不明白我们如何获得 SelectedArtist 值。我插入了这段代码并对其进行了测试,它一直给我null ...我试图从我拥有的Artits列表中将artistName分配给SelectedArtist,但这并不成功:

有人可以帮我在检查 SelectedArtist 值是否为空之前找到它吗

我目前有一个包含艺术家姓名的组合框,一旦选择了艺术家,我需要将其绑定到另一个专辑组合框。

在我看来,这些设置如下: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));}
4

2 回答 2

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设置为“PropertyChanged”。

于 2013-05-27T10:47:27.327 回答
0

此线程中有此问题的延续并将其标记为已回答 'System.Collections.ObjectModel.ObservableCollection 的最佳重载方法匹配有一些无效参数

于 2013-05-28T13:09:56.413 回答