reactiveuiavaloniauiavalonia

Avalonia ReactiveUI: How to Refresh UI When ObservableCollection of ViewModels Updates in Parent ViewModel?


I’ve created a parent container called HomeViewModel, which contains an ObservableCollection of two GameViewModel instances. Each GameViewModel corresponds to a specific game and includes a button to toggle a watcher for a particular game folder.

The problem is that although the commands associated with the buttons work correctly, the UI doesn’t refresh immediately when I interact with them. Instead, the UI updates only when I change routes. I’ve tried various approaches to resolve this issue, but I’m still unsure what’s causing it.

My HomeViewModel implements the ReactiveObject and IRoutableViewModel as in the tutorials of the ReactiveUi to have an router navigation.

Here's the code:

public class HomeViewModel : ReactiveObject, IRoutableViewModel

// Some other code

    private ObservableCollection<GameViewModel> _games = new()
    {
        new GameViewModel(new Game() { Name = "Game1", Type = GameType.Game1 }),
        new GameViewModel(new Game() { Name = "Gam2", Type = GameType.Game2 }),
    };

    public ObservableCollection<GameViewModel> Games
    {
        get => _games;
        set => this.RaiseAndSetIfChanged(ref _games, value);
    }
//HomeView.axaml
        <ListBox Grid.Row="1" ItemsSource="{Binding Games}"
                 MinWidth="250">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
// GameViewMode.cs
public class GameViewModel : ViewModelBase 
{
    public GameViewModel()
    {
    }

    public GameViewModel(Game game)
    {
        Name = game.Name;
        Path = game.Path;
        Type = game.Type;
        
        SelectPath = ReactiveCommand.Create(SelectAnPath);
        ToggleWatcher = ReactiveCommand.Create(ToggleEnabled);

    }
    
    public ReactiveCommand<Unit, Unit> SelectPath { get; }

    public ReactiveCommand<Unit, Unit> ToggleWatcher { get; }


    private void SelectAnPath()
    {
        Debug.WriteLine("Path Clicked " + Name);
        Path = Guid.NewGuid().ToString().Substring(0, 10);
    }

    private void ToggleEnabled()
    {
        Debug.WriteLine("Watcher toggle click");
        _isWatcherToggled = !_isWatcherToggled;
    }

    private string _name;

    public string Name
    {
        get => _name;
        set => this.RaiseAndSetIfChanged(ref _name, value);
    }

    private string _path;

    public string Path
    {
        get => _path;
        set => this.RaiseAndSetIfChanged(ref _path, value);
    }

    private GameType _type;

    public GameType Type
    {
        get => _type;
        set => this.RaiseAndSetIfChanged(ref _type, value);
    }

    private bool _isWatcherToggled;

    public bool IsWatcherToggled
    {
        get => _isWatcherToggled;
        set => this.RaiseAndSetIfChanged(ref _isWatcherToggled, value);
    }
}

// GameView.axaml
    <StackPanel Width="200">
        <Border CornerRadius="10" ClipToBounds="True">
            <Panel Background="#7FFF22DD">
                <!-- <Image Width="200" Stretch="Uniform" Source="{Binding Cover}" /> -->
                <!-- IsVisible="{Binding Cover, Converter={x:Static ObjectConverters.IsNull}}" -->
                <Panel Height="200">
                    <PathIcon Height="75" Width="75" Data="{StaticResource GamesRegular}"></PathIcon>
                </Panel>
                <Button VerticalAlignment="Bottom"
                        HorizontalAlignment="Left" 
                        CornerRadius="10"
                        Command="{Binding ToggleWatcher}"
                        Classes.btn="{Binding IsWatcherToggled}">
                    <Button.Styles>
                        <Style Selector="Button.btn">
                            <Setter Property="Background" Value="Bisque"></Setter>
                        </Style>
                    </Button.Styles>
                    <PathIcon Height="25"
                              Width="25" 
                              Data="{StaticResource PowerRegular}"
                              Classes.toggled="{Binding IsWatcherToggled}"
                    >
                        <PathIcon.Styles>
                            <Style Selector="PathIcon">
                                <Setter Property="Foreground" Value="Red"></Setter>
                            </Style>
                            <Style Selector="PathIcon.toggled">
                                <Setter Property="Foreground" Value="LimeGreen"></Setter>
                            </Style>
                            
                        </PathIcon.Styles>
                    </PathIcon>
                </Button>
                <Button VerticalAlignment="Bottom"
                        HorizontalAlignment="Right"
                        CornerRadius="10"
                        Command="{Binding SelectPath}">
                    <PathIcon Height="25" Width="25" Data="{StaticResource FolderLinkRegular}"></PathIcon>
                </Button>
            </Panel>
        </Border>
        <TextBlock HorizontalAlignment="Center" Text="{Binding Name}" />
        <TextBlock HorizontalAlignment="Center" />
    </StackPanel>

my MainWindowView

        <Grid Margin="0, 25,0,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="125" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <rxui:RoutedViewHost Grid.Column="1"
                                 Router="{Binding Router}"
                                 
                                 >
                <!-- Tela Mudavel aqui -->
                <rxui:RoutedViewHost.DefaultContent>
                    <TextBlock Text="Default Content"
                               HorizontalAlignment="Center"
                               VerticalAlignment="Center" />
                </rxui:RoutedViewHost.DefaultContent>
                <rxui:RoutedViewHost.ViewLocator>
                    <!-- App View Locator -->
                    <rhythmScrobbler:SimpleViewLocator />
                </rxui:RoutedViewHost.ViewLocator>
            </rxui:RoutedViewHost>
            <StackPanel Grid.Column="0" Margin="5, 10, 0, 0" >
                <Button HorizontalAlignment="Center"
                        Command="{Binding NavigateHome}">
                    Home
                </Button>
                <Separator />

            </StackPanel>

        </Grid>

my MainWindowViewModel

public class MainWindowViewModel : ReactiveObject, IScreen
{
    // The Router associated with this Screen.
    // Required by the IScreen interface.
    public RoutingState Router { get; } = new RoutingState();

    private ObservableCollection<IRoutableViewModel> ViewModelCollection { get; }

    public ReactiveCommand<Unit, IRoutableViewModel> NavigateHome { get; }

    public ReactiveCommand<Unit, IRoutableViewModel> NavigateLog { get; }

    public MainWindowViewModel()
    {
        ViewModelCollection = new ObservableCollection<IRoutableViewModel>
        {
            new HomeViewModel(this),
            //new SecondViewModel(this)
            // Add other view models here
        };

        // NavigateCommand = ReactiveCommand.CreateFromTask<IRoutableViewModel>(NavigateToViewModel);
        NavigateHome = ReactiveCommand.CreateFromObservable(
            () => Router.Navigate.Execute(ViewModelCollection[0])
        );

        NavigateLog = ReactiveCommand.CreateFromObservable(
            () => Router.Navigate.Execute(new SecondViewModel(this))
        );

        Router.Navigate.Execute(ViewModelCollection[0]);
    }
    
}

I hope someone can clarify me what i'm doing wrong here, and how to update it.


Solution

  • The problem was that i was not using the property that implements INotifyPropertyChanged

    Old code in GameViewModel

        private void ToggleEnabled()
        {
            Debug.WriteLine("Watcher toggle click");
            _isWatcherToggled = !_isWatcherToggled;
        }
    
        private bool _isWatcherToggled;
    
        public bool IsWatcherToggled
        {
            get => _isWatcherToggled;
            set => this.RaiseAndSetIfChanged(ref _isWatcherToggled, value);
        }
    

    Later

      private void ToggleEnabled()
        {
            Debug.WriteLine("Watcher toggle click");
            IsWatcherToggled= !IsWatcherToggled;
        }