Data disappears from ListView after assigning new

2019-08-15 03:03发布

I have the following ListView:

<ListView 
    Grid.Row="1" 
    ItemsSource="{Binding MeditationDiary}" >
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid Width="{Binding ElementName=ListViewHeaders, Path=ActualWidth}" >
                <Grid.ColumnDefinitions>
                    <ColumnDefinition  />
                    <ColumnDefinition  />
                </Grid.ColumnDefinitions>
                <TextBlock 
                    Grid.Column="0" 
                    Text="{Binding StartTime}" />
                <TextBlock 
                    Grid.Column="1" 
                    Text="{Binding TimeMeditated}" />
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

This is bound to a MeditationDiary property of type MeditationDiary consisting of MeditationEntries:

public class MeditationDiary : Collection<MeditationEntry> { }

public class MeditationEntry
{
    public DateTime StartTime { get; set; }
    public TimeSpan TimeMeditated { get; set; }
}

The ListView binds to this MeditationDiary:

private MeditationDiary _meditationDiary;
public MeditationDiary MeditationDiary
{
    get
    {
        RaisePropertyChanged(nameof(MeditationDiary));
        return _meditationDiary;
    }
    set
    {
        _meditationDiary = value;
        RaisePropertyChanged(nameof(MeditationDiary));
    }
}

Strangely enough when I assign a new MeditationDiary object to the property (which contains data with MeditationEntries) the ListView does no longer display data.

I'm assigning the new MeditationDiary object in the UpdateDiary method which is called after adding an entry:

private async void UpdateDiary()
{
    var latestDiary = await _repository.GetAsync();
    MeditationDiary = latestDiary;
}

Why can this be and how can it be fixed?

1条回答
趁早两清
2楼-- · 2019-08-15 03:39

This is most likely the culprit that's messing up your binding:

MeditationDiary = latestDiary;

Instead, try clearing out the current collection and then adding the new values to it:

MeditationDiary.Clear();

foreach (var entry in latestDiary)
    MeditationDiary.Add(entry);

You'll probably have to call RaisePropertyChanged on the collection after you add the new items.

As a side note, you could replace MeditationDiary with an ObservableCollection<MeditationEntry>, which automatically notifies the UI when you add/remove items in it.

查看更多
登录 后发表回答