0
votes

I use one window to change the data, while using another window(MainWindow) to show the data.

Unexpectedly, when MainWindowViewModel catches the PropertyChanged event and RaisePropertyChanged to update MainWindow view, nothing happened in the view.

In the debugger, I found the MainWindowViewModel property has changed,and Debug has printed the message, but view not change.

I'm using Mvvmlight. Sorry for my poor English. I'd appreciate it if you could help me. XD!

Here is the View code:

<Window x:Class="OneTimetablePlus.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:OneTimetablePlus.Views"
        xmlns:tb="http://www.hardcodet.net/taskbar"
        mc:Ignorable="d"
        Title="MainWindow" Height="730" Width="91.52"
        AllowsTransparency="True"
        WindowStyle="None"
        Background="Transparent"
        ShowInTaskbar="False"
        Topmost="True"
        ResizeMode="NoResize"
        DataContext="{Binding Main, Source={StaticResource Locator}}"
>
    
    <ListBox ItemsSource="{Binding TodayDayCourses}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding ShowName}" Style="{StaticResource LargeText}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

</Window>

Here is the ViewModel code:

public class MainViewModel : ViewModelBase
{
    public MainViewModel(IDataProvider dataProvider)
    {
        DataProvider = dataProvider;

        dataProvider.PropertyChanged += (sender, e) =>
        {
            if (e.PropertyName == GetPropertyName(() => dataProvider.TodayDayCourse))
            {
                Debug.Print("Catch PropertyChanged TodayDayCourse");
                RaisePropertyChanged(() => TodayDayCourses);
            }
        };
    }

    public List<Course> TodayDayCourses => DataProvider.TodayDayCourse2;

    public IDataProvider DataProvider { get; }
}
1
The UI won't update when DataProvider.TodayDayCourse2 always returns the same collection instance (which would effectively not be a "property change"). Try a simple workaround: => DataProvider.TodayDayCourse2.ToList(); - Clemens
It worked! Thank you very much! - Kelatte
@Kelatte write a new answer instead of adding it to the question. - Sabito 錆兎

1 Answers

0
votes

As Clemens said, we should use => DataProvider.TodayDayCourse2.ToList() instead of => DataProvider.TodayDayCourse2. Because the latter always returns the same instance, while is not a property changed.