Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
844 views
in Technique[技术] by (71.8m points)

c# - Reverse order of ObservableCollection

I have ObservableCollection that contains a custom object. Normally the items get added at the end of the list

What i am looking for:

  • Items being added from the beginning of the list.
  • This may only show in the UI, my entire program is already using the positions of data inside this list. So the objects inside it may not change order in the code behind.

This ObservableColection holds Button objects (custom styled). These buttons are being displayed in a ListBox and inside a StackPanel with Horizontal layout (so the buttons get nicely placed after each other).

Problem:

Every button that gets created receives a DateTime. A newly added button always has a more recent date then the button before that. All the calculations for this are happening inside a timer(currently running every second).

So i am basically sorting on this time, but after like 3 buttons suddenly a button gets placed at right hand side (instead of the left hand side).

For example:

Btn3: 14:15:45(correct) Btn4: 14:16:00(wrong) Btn2: 14:15:32(correct) Btn1: 14:04:17(correct)

The first 3 buttons get added properly at the beginning of the list each time. And suddenly the fourth item is being added at the second place. It seems it is not always comparing the time? Every time a button gets created the CollectionViewSource method gets called upon.

Is there something wrong with the CollectionViewSource or is there a better way of handling this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For grins would you try the sort in XAML? I know these are not the same names but this is from working code. I am not sorting on date but I have done hundreds of adds and removes from DocProps and the sort does not break.

        <ListBox.DataContext>
            <CollectionViewSource Source="{Binding Path=DocProps}">
                <CollectionViewSource.SortDescriptions>
                    <scm:SortDescription PropertyName="Date" Direction="Desc" />
                </CollectionViewSource.SortDescriptions>
            </CollectionViewSource>
        </ListBox.DataContext>

My other thought is that it may be sorting a string representation of date and getting it wrong. Maybe create an index 001 - 00n to sort on.

I added a date to this collection and it worked from me. But had to make the date a sortable format.

     Text="{Binding Path=Date, Mode=OneWay, StringFormat={}{0:s}}"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...