开发者

Binding a hierarchical data model to a DataGrid

I have a hierarchical data structure for a simple WPF application as follows:

A TvshowCollection开发者_开发百科 object contains Tvshow objects. Each Tvshow object contains an EpisodeCollection object, which in turn contains Episode objects. The model makes heavy use of INotifyPropertyChanged.

I need to display a list of all of the Episode objects in a grid, along with the name of the Tvshow.

If I take all of the Episodes from the structure and bind them to the ItemsSource of the grid it is easy to bind each property of the Episode to a column, but how can I then bind one of the columns to the related Tvshow Name property which is higher up in the hierarchy?

Can I flatten the data somehow in a ViewModel?

I hope this makes sense.

Thanks!


edit:

Thanks MAW74656, this is what i want the end result to be - all of the Episodes in the system displayed, with the Tvshow details repeated in the grid (Airdate is a property of Episode):

Image here: http://i.stack.imgur.com/SY1Ib.png

I have this working now, to a degree, but not in a way that I particularly like. I've put a property on the ViewModel for the Grid to return an object containing the information I need:

public class TvshowGridViewModel : BaseViewModel
{
    private Repository _repo;

    private TvshowCollection _allTvshows;

    public object AllTvshows
    {
        get
        {
            var flatList = from tvshow in _allTvshows
                           from episode in tvshow.Episodes
                           select new { TvshowName = tvshow.Name, EpisodeName = episode.Name, EpisodeNumber = episode.Number, EpisodeAirdate = episode.Airdate };
            return flatList;
        }
    }

    public TvshowGridViewModel()
    {
        _repo = new Repository("");
        _allTvshows = _repo.Tvshows;
    }
}

But I don't seem to be able to make this a two-way binding. Is there a better way?


Try to use objects instead of strings:

var flatList = from tvshow in _allTvshows
               from episode in tvshow.Episodes
               select new { TvShow = tvshow, Episode = episode};

DataGrid should have explicitly specified columns:

<sdk:DataGridTextColumn Binding="{Binding TvShow.Name}" Header="Tv Show"/>
<sdk:DataGridTextColumn Binding="{Binding Episode.Name}" Header="Episode Name"/>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜