开发者

Using LINQ to get 1-2-3 scores and bind them to View

I have a table with players and scores (Name:Mike Score:10, Name:Peter Score:5, etc) and a View with 3 pictures of a bronze, silver and gold medal. Underneath each picture I want to display the playername(s) of the winners each week / round. Could well be that there are multiple bronze, silver or gold scores.

In my TotalViewModel I have an ObservableCollection for all the Total Scores:

public const string TotalsPropertyName = "Totals";

private ObservableCollection<TotalViewModel> _totals;

public ObservableCollection<TotalViewModel> Totals
{
    get
    {
        return _totals;
    }
    set
    {
        if (_totals == value)
            return;
        _totals = value;
        RaisePropertyChanged(TotalsPropertyName);
    }
}

I wanted to use a IEnumerable because of the multiple numbers one, two, three score:

public IEnumerable<TotalViewModel> FirstOne { get; private set; }

private void UpdateFirstOne()
{
    this.FirstOne = this.Totals.Where(elem => elem.Model.score > 0).OrderByDescending(e => e.Model.score);
}

private void Totals_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    try
    {
        this.UpdateFirstOne();
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.ToString());
    }
}

The DataContext of my View is working fine for the straightforward bindings, it's set in the UserControl:

DataContext="{Binding MainTotal, Source={StaticResource Locator}}

But the results aren't displayed in my DataGrid (guess I'm making a stupid mistake here):

<data:DataGrid ItemsSource="{Binding FirstOne, Mode=OneWay}" AutoGenerateColumns="true" Height="100" Name="dataGrid1" Width="120" />

So I have 2 questions:

  1. How do I get the desired collection of number 1/2/3 scores开发者_运维知识库?
  2. How do I get them in my View?

Thanks.


Well I wont get into the data binding bit but a linq query to extract the top three could be something like this:

var topThreeScoringNameLists =
    Totals
        .GroupBy(x => x.Model.Score)
        .OrderByDescending(x => x.Key)
        .Take(3)
        .Select(x => 
            String.Join(", ", x.Select(y => y.Model.Name).ToArray()));


You're binding to FirstOne so you need to do a propertychanged for that property.

public IEnumerable<TotalViewModel> FirstOne 
{ 
    get
    {
        return _firstOne;
    }
    private set
    {
        _firstOne = value;
        RaisePropertyChanged("FirstOne");
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜