Home > Software engineering >  C# CommunityToolkit.Mvvm ObservableProperty on a list
C# CommunityToolkit.Mvvm ObservableProperty on a list

Time:08-22

I want to try the Community Toolkit 8.0 the MVVM part.

I have a very simple application:

.... 
       d:DataContext="{d:DesignInstance Type=local:MainWindowViewModel}"
.... 
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="12*" />
        </Grid.RowDefinitions>
        <Button x:Name="ButtonDirectory" Grid.Row="0" Grid.Column="0" Margin="50 2 0 2" Width="200" Content="List Directory" Command="{Binding ClickButtonListDirectoryCommand, Mode=OneWay}" />
        <ListView x:Name="ListViewDirectories" Grid.Row="1" Grid.Column="0" ItemsSource="{Binding DirectoriesNames}"  />
    </Grid>

and this is my viewmodel:

public partial class MainWindowViewModel : ObservableObject
{
    [ObservableProperty]
    List<string> _directoriesNames = new();

    [RelayCommand]
    private void ClickButtonListDirectory()
    {
        this.DirectoriesNames.Add("Hello");
    }
}

This construct works, when I use string instead of a list - but obviously I want to use something like a list when my view component is a ListView.

The directoriesNames itself gets updated (saw that in the debugger) but it's not displayed in the view (ListView).

Can someone help me out with that?

Thanks.

CodePudding user response:

Change your List to ObservableCollection.

This code:

[ObservableProperty]
List<string> _directoriesNames = new();

Will notify the UI when the DirectoriesNames itself is changed but the only change you are making to DirectoriesNames is instantiating it.

You can use a ObservableCollection to notify the UI when you add or remove items.

CodePudding user response:

You need to use ObservableCollection :-

ObservableCollection<string> DirectoriesNames = new();

  • Related