Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Notifications
Mark all as read
Q&A

WPF MVVM ListBox not updating

+4
−0

I am trying to combine MVVM in WPF using Microsoft.Toolkit.MVVM. Somethings are working as expected. The text boxes bind to fields and update in both directions. The button command executes and changes the values of the instance and in the box. The ListBox shows the initial values.

However, the ListBox does not show the values after the execute changes the List.

This little demo shows the problem I'm having. Here is the code (install Microsoft.Toolkit.Mvvm).

Demo.cs

public class Demo
{
    public int Value { get; set; } = 2;
    public List<int> AllValues { get; set; } = new List<int> { 1, 2 };
}

DemoViewModel

public class DemoViewModel : ObservableObject
{
    private Demo _demo;

    public DemoViewModel()
    {
        _demo = new Demo();
        IncrementCommand = new RelayCommand(DoIncrement);
    }

    public Demo Demo
    {
        get => _demo;
        set
        {
            SetProperty(ref _demo, value);
        }
    }

    public IRelayCommand IncrementCommand { get; }

    private void DoIncrement()
    {
        _demo.Value++;
        _demo.AllValues.Add(_demo.Value);
        OnPropertyChanged("Demo");
    }
}

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new DemoViewModel();
    }
}

Grid portion of MainWindow.xaml.

<Grid Margin="0,0,0,10">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <TextBox Name="txtNumber" Text="{Binding Path=Demo.Value}"></TextBox>
    <Button Grid.Row="1" Name="btnIncrement" Command="{Binding IncrementCommand}">Increment</Button>
    <ListBox Grid.Row="2" ItemsSource="{Binding Path=Demo.AllValues}"></ListBox>
</Grid>

What needs fixing so that the ListBox updates after the button is clicked with the new list of values?

Thank you.

Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

2 comment threads

General (1 comment)
Setting with a new list instead of extending the existing list (2 comments)

2 answers

+4
−0

List<T> is not observable. In other words, List<T> does not offer a mechanism through which it could signal that its content has changed.

If it is possible/permissible to modify the Demo class, then use ObservableCollection<T>, BindingList<T> or something similar instead. As their type names suggests, using one of them instead of List<T> will allow ListBox to listen to change notifications provided by these collections. This basically allows the ListBox to automatically update whenever items are added to, removed from or replaced in one of these collection types.

While Alexei's answer will work for simple cases, note that replacing the List<T> instance and raising a respective property change event will trigger processing of all list items by any UI element the list or a list item is bound to. Depending on the complexity of the GUI (binding relationships, templates, etc...), specifically the work required to arrange and draw the representation(s) of an item in the UI, this approach might possibly have a noticeable performance impact when the list contains more than a few dozen items.

Using ObservableCollection<T> or BindingList<T> will not require raising the property change event. It will normally also not suffer from the same potential performance impact, since the ObservableCollection<T> / BindingList<T> typically tells which items have been added to, removed from or replaced in it, thus the ListBox (and other related UI elements) is able to limit its layout and drawing work to the specific list items that have been added/removed/replaced.

Since the Value property of the Demo class is also participating in data binding while its value can change, property change notifications should be implemented for this property as well. For example by making the Demo class an Observable and implement the getter/setter of the Value property accordingly; as i did in my Demo class example here (and i did it for the AllValues property too, because it also has a setter):

public class Demo : Observable
{
    public int Value
    {
        get => _value;
        set => SetProperty(ref _value, value);
    }
    private int _value;

    public ObservableCollection<int> AllValues
    {
        get => _allValues;
        set => SetProperty(ref _allValues, value);
    }
    private ObservableCollection<int> _allValues = new ObservableCollection<int> { 1, 2 };
}

Finally, the DoIncrement() method could get rid of the (now pointless) OnPropertyChanged notification:

private void DoIncrement()
{
    _demo.Value++;
    _demo.AllValues.Add(_demo.Value);
}

If however an alteration of the Demo class is not possible, but creating a new Demo instance in the view model is okay, then instead of making a copy of the list (relatively expensive when the list becomes larger) i would perhaps rather opt for making a copy of the Demo instance (remains relatively cheap regardless of list size):

private void DoIncrement()
{
    var updatedValue = Demo.Value + 1;
    var updatedList = Demo.AllValues;
    updatedList.Add(updatedValue);
 
    Demo = new Demo
    {
        Value = updatedValue,
        AllValues = updatedList
    };

    // the setter of the Demo property should take care of
    // property change notifications, so no OnPropertyChanged here...
}

The possible performance implications i mentioned above still apply to this approach, though, so choose your "poison" well...

Why does this post require moderator attention?
You might want to add some details to your flag.

0 comment threads

+4
−0

I haven't worked in WPF for a long time, but you might try setting a new list (clone the old one and add the new element) instead of adding the element to the existing list:

_demo.Value++;
var newList = new List(_demo.AllValues);
newList.Add(_demo.Value);
_demo.AllValues = newList;
OnPropertyChanged("Demo");

I do not how WPF & MVVCM work internally, but this is a usual patterns in other frameworks such as Angular, mandatory when working with a Redux-like pattern (you never directly mutate the state, but clone in + make changes)

Why does this post require moderator attention?
You might want to add some details to your flag.

0 comment threads

Sign up to answer this question »

This community is part of the Codidact network. We have other communities too — take a look!

You can also join us in chat!

Want to advertise this community? Use our templates!

Like what we're doing? Support us! Donate