In a simple WPF XAML UI a list of items is shown:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="450" Width="800">
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Text}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Window>
The data is in the C# view model:
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
Items.Add(new MyItem());
Items.Add(new MyItem());
Items.Add(new MyItem());
Items.Add(new MyItem());
Loaded += async (s, e) =>
{
while (true)
{
await Task.Delay(1000); // Items could be changed here instead
Items.ResetBindings(); // Let UI know about the added/removed/reordered/modified items
}
};
}
public BindingList<MyItem> Items { get; } = new BindingList<MyItem>();
}
public class MyItem : INotifyPropertyChanged
{
public string Text { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}
The items can change automatically, so Items.ResetBindings();
is called to makes these changes appear in the UI. But this also breaks the UI: The focus and any modification of the current item by the user just disappear!
How can the binding list be updated without resetting the UI controls?