Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on WPF MVVM ListBox not updating
Post
WPF MVVM ListBox not updating
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.
2 comment threads