更改数据源后取消排序

时间:2016-03-22 08:39:54

标签: wpf silverlight datagrid

我有Silverlight应用程序,每1秒钟更改一次可观察的集合,但发生的事情是排序后排序被取消。 我怎么解决呢? 这种情况每1秒发生一次:

private async void ClockTimerOnTick(object sender, EventArgs eventArgs)
{
    var allOpenTrades = await NewAPI.GetOpenTrades();
    var openLongTrades = allOpenTrades.Where(x => x.gameType == (int)GameType.LongTerm);
    LongTermModel.Open = new ObservableCollection<OpenTranasctionLongTerm>
    (openLongTrades.Select(x => new OpenTranasctionLongTerm
    {                   
        isPut = x.CallPutStatusId == 2,
        DateTraded = x.TransactionCreatedOn.ToLocalTime(),
        Expiration = x.optionExpirationTime.ToLocalTime(),
        Payout = x.OptionWinReturn,
        Security = x.OptionName,
        StrikePrice = x.TransactionQuote,
        Traded = x.Amount,
        Currency = UserCurrency,
        isCall = x.CallPutStatusId == 1,
        Type = x.CallPutStatusId == 1 ? "Call" : "Put"
    }).ToList());
}

1 个答案:

答案 0 :(得分:1)

正如我可以看到你重置(创建一个新的可观察集合)你的集合每个计时器滴答,因此在我看来,DataGrid的ItemsSource的sort description被清除。我认为如果用下一个代码替换你的重新创建(创建新的可观察集合)代码,它将帮助你保留原始排序描述。

新的ClockTimerOnTick方法代码

    private void ClockTimerOnTick(object sender, EventArgs eventArgs)
    {
        var allOpenTrades = NewAPI.GetOpenTrades();
        var openLongTrades = allOpenTrades.Where(x => x.gameType == (int)GameType.LongTerm).ToList();
        //I'm assuming here that the LongTermModel.Open is an observable collection
        LongTermModel.Open.Clear();
        openLongTrades.ForEach(term =>
        {
            LongTermModel.Open.Add(new OpenTranasctionLongTerm
            {
                isPut = x.CallPutStatusId == 2,
                DateTraded = x.TransactionCreatedOn.ToLocalTime(),
                Expiration = x.optionExpirationTime.ToLocalTime(),
                Payout = x.OptionWinReturn,
                Security = x.OptionName,
                StrikePrice = x.TransactionQuote,
                Traded = x.Amount,
                Currency = UserCurrency,
                isCall = x.CallPutStatusId == 1,
                Type = x.CallPutStatusId == 1 ? "Call" : "Put"
            });
        });
    }

在这里,我们只需清除并重新填充每个计时器滴答的LongTermModel.Open集合。

问候。