The crux of the problem - ListBox is not updated externally when editing an item ...
ListBox Code:
<ListBox Name="ListBoxSyncItem" ItemsSource="{Binding}"> <ListBox.ItemTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding Name}"/> <Grid.ContextMenu> <ContextMenu> <MenuItem Header="Изменить" Click="MenuItem_Update_OnClick"></MenuItem> <MenuItem Header="Удалить" Click="MenuItem_Delet_OnClick"></MenuItem> </ContextMenu> </Grid.ContextMenu> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> ObservableCollection is written in the DataContext window
private readonly ObservableCollection<ListBoxItemSync> _listBoxItemSyncs = new ObservableCollection<ListBoxItemSync>(); ... public MainWindow() { ... ListBoxSyncItem.DataContext = _listBoxItemSyncs; ListBoxItemSync Code:
private class ListBoxItemSync { public string Name { get; set; } public SyncItem SyncItem { get; set; } } MenuItem_Update_OnClick method (Called via the context menu of the ListBox element):
private void MenuItem_Update_OnClick(object sender, RoutedEventArgs e) { var targetListItem = (ListBoxItemSync) ((MenuItem) sender).DataContext; var window = new CreateSyncItemWindow(targetListItem.SyncItem); //if (window.ShowDialog() == true) //{ // targetListItem.SyncItem = window.GetNewItem(); // targetListItem.Name = targetListItem.SyncItem.Name; //} if (window.ShowDialog() == true) { _listBoxItemSyncs.Remove(targetListItem); _listBoxItemSyncs.Add(new ListBoxItemSync() {SyncItem = window.GetNewItem(), Name = window.GetNewItem().Name }); } } In CreateSyncItemWindow, a new SyncItem item is created, returned via the GetNewItem method.
In the commented piece of code is a non-working option. It updates the data in the _listBoxItemSyncs collection (its items should display a ListBox), but the appearance of the ListBox does not change.
The second option (the one that is not commented out) will remove the old item from the collection and add a new one. This will update the appearance of the ListBox, but I don’t like this method because the "updated" element will appear at the end of the list anyway, and look for the number of the old element before deleting it ... There will be a lot of common code.
How to be with 1 option?