Обновить элементы списка из другой ViewModel

Я схожу с ума, пытаясь понять, почему мой код не работает.

Я удаляю или добавляю элементы в список в EditIncidentViewModel и использую IEventAggregator для передачи этого списка в поле со списком в DisplayIncidentViewModel, но не могу обновить элементы.

В DisplayIncidentViewModel изначально список заполняется путем анализа текстового файла, как я могу получить обновленный список?

Вот DisplayIncidentViewModel:

namespace WpfUI.ViewModels
{
public class DisplayIncidentViewModel : Screen, IHandle<BindableCollection<Incident>>
{
    private Incident _selectedIncident;
    private string _firstName;
    private string _resolutionText;
    private bool _hasOptions;
    private bool _isChecked;
    private string output = "";
    private string _text;
    private IEventAggregator _events;


    public string FirstName
    {
        get { return _firstName; }
        set
        {
            _firstName = value;
            NotifyOfPropertyChange(() => FirstName);
            NotifyOfPropertyChange(() => ResolutionText);
        }
    }

    public string ResolutionText
    {
        get { return CreateResolutionText(); }
        set
        {
            _resolutionText = value;
            NotifyOfPropertyChange(() => ResolutionText);
        }
    }

    public bool HasOptions
    {
        get
        {
            if (SelectedIncident == null)
            {
                Incident inc = new Incident();
                SelectedIncident = inc;
                _isChecked = false;
                return false;
            }
            if (string.IsNullOrWhiteSpace(SelectedIncident.Option))
            {
                _isChecked = false;
                return false;
            }
            else return true;
        }
        set
        {
            _hasOptions = value;
            NotifyOfPropertyChange(() => HasOptions);

        }
    }

    public bool IsChecked
    {
        get { return _isChecked; }

        set
        {
            if (_isChecked == value) return;
            _isChecked = value;
            NotifyOfPropertyChange(() => IsChecked);
            NotifyOfPropertyChange(() => ResolutionText);
        }
    }

    public string Text
    {
        get { return _text; }
        set {
            _text = value;
            NotifyOfPropertyChange(() => Text);
        }
    }


    public DisplayIncidentViewModel(IEventAggregator events)
    {
        _events = events;
        var parser = new JsonParser();
        parser.JsonLoadFile();
        var list = parser.SortIncidentsByName();

        foreach (var item in list)
        {
            Incidents.Add(new Incident
            {
                Name = item.Name,
                Description = item.Description,
                OtherDescription = item.OtherDescription,
                Option = item.Option
            });
        }
        Incidents.Refresh();
    }

    #region Combobox
    // this is the backend that fires-up combobox with the values from json file

    public BindableCollection<Incident> Incidents { get; set; } = new BindableCollection<Incident>();


    public Incident SelectedIncident
    {
        get { return _selectedIncident; }
        set
        {
            _selectedIncident = value;
            IsChecked = false;
            NotifyOfPropertyChange(() => SelectedIncident);
            NotifyOfPropertyChange(() => ResolutionText);
            NotifyOfPropertyChange(() => HasOptions);
            NotifyOfPropertyChange(() => Text);
        }
    }
    #endregion


    public string CreateResolutionText()
    {

        if (SelectedIncident == null)
        {
            Incident inc = new Incident();
            SelectedIncident = inc;
            var nou = inc.Description;

            SelectedIncident.Description = nou;
            NotifyOfPropertyChange(() => SelectedIncident);

        }
        if (FirstName != "" && !string.IsNullOrWhiteSpace(SelectedIncident.Name))
        {
            if (!IsChecked)
            {
                output = $"{ FirstName },{Environment.NewLine}{SelectedIncident.Description}{Environment.NewLine}{Environment.NewLine}{ Globals.GetUsersFirstName(Globals.UserName) }";
                Clipboard.SetText(output);

            }

            if (IsChecked)
            {
                output = $"{ FirstName },{Environment.NewLine}{SelectedIncident.OtherDescription}{Environment.NewLine}{Environment.NewLine}{ Globals.GetUsersFirstName(Globals.UserName) }";
                Clipboard.SetText(output);
            }
            switch (SelectedIncident.Name)
            {
                case "Message":
                    Text = $"Dummy text here";
                    _events.PublishOnUIThread(new StatusText(Text));
                    break;
                default:
                    _events.PublishOnUIThread(new StatusText($"Text copied to cliboard"));
                    break;
            }

        }
        return output;

    }



    public void Handle(BindableCollection<Incident> message)
    {
        Incidents.Clear();
        Incidents = message;
        NotifyOfPropertyChange(() => Incidents);
    }
}

}

Вот EditIncidentViewModel:

public class EditIncidentViewModel : Screen
{
    private IEventAggregator _events;
    private Incident _selectedIncident;
    public BindableCollection<Incident> Incidents { get; set; } = new BindableCollection<Incident>();
    private string _text;
    private string _incidentDescription;
    private string _incidentName;
    private string output = "";

    public Incident SelectedIncident
    {
        get { return _selectedIncident; }
        set
        {
            _selectedIncident = value;
            NotifyOfPropertyChange(() => SelectedIncident);
            NotifyOfPropertyChange(() => IncidentDescription);
           // NotifyOfPropertyChange(() => HasOptions);
            NotifyOfPropertyChange(() => Text);
            NotifyOfPropertyChange(() => IncidentName);
        }
    }

    public string IncidentDescription
    {
        get { return GetIncidentDescription(); }
        set
        {
            _incidentDescription = value;
            NotifyOfPropertyChange(() => IncidentDescription);
        }
    }

    #region Constructor
    public EditIncidentViewModel(IEventAggregator events)
    {
        _events = events;
        var parser = new JsonParser();
        parser.JsonLoadFile();
        var list = parser.SortIncidentsByName();

        foreach (var item in list)
        {
            Incidents.Add(new Incident
            {
                Name = item.Name,
                Description = item.Description,
                OtherDescription = item.OtherDescription,
                Option = item.Option
            });
        }

    }
    #endregion

    public string Text
    {
        get { return _text; }
        set
        {
            _text = value;
            NotifyOfPropertyChange(() => Text);
        }
    }


    public string IncidentName
    {
        get {
            if (SelectedIncident == null)
            {
                SelectedIncident = new Incident
                {
                    Name = ""
                };
            }

            return SelectedIncident.Name;
        }

        set {
            _incidentName = value;
            NotifyOfPropertyChange(() => IncidentName);

        }
    }


    public string GetIncidentDescription()
    {

        if (SelectedIncident == null)
        {
            Incident inc = new Incident();
            SelectedIncident = inc;
            var nou = inc.Description;

            SelectedIncident.Description = nou;
            NotifyOfPropertyChange(() => SelectedIncident);

        }

        output = SelectedIncident.Description;

        return output;

    }


    public void SaveIncident()
    {
        var newIncident = new Incident();

        if (!string.IsNullOrWhiteSpace(_incidentName) || !string.IsNullOrWhiteSpace(_incidentDescription))
        {
            // Get SelectedIncident Name
            newIncident.Name = _incidentName;
            // Get SelectedIncident Description
            newIncident.Description = _incidentDescription;
            // Create a new Incident with the new properties
            newIncident.OtherDescription = "dummy text here";
            newIncident.Option = "";
            // Incidents.Clear();
            Incidents.Remove(SelectedIncident);
            Incidents.Add(newIncident);

            Incidents.Refresh();
            // Save to file
            string strResultJson = JsonConvert.SerializeObject(Incidents);
            File.WriteAllText(Path.Combine(Environment.CurrentDirectory, "Data", "configuration.json"), strResultJson);
            NotifyOfPropertyChange(() => IncidentDescription);
            NotifyOfPropertyChange(() => IncidentName);

        }

        if (string.IsNullOrWhiteSpace(_incidentDescription) || _incidentDescription == IncidentDescription)
        {
            Incidents.Remove(SelectedIncident);
            Text = $"Incident with name { SelectedIncident.Name } was deleted.";
            _events.PublishOnUIThread(new StatusText(Text));

            Incidents.Refresh();
            // Save to file
            string strResultJson = JsonConvert.SerializeObject(Incidents);
            File.WriteAllText(Path.Combine(Environment.CurrentDirectory, "Data", "configuration.json"), strResultJson);
            NotifyOfPropertyChange(() => IncidentDescription);
            NotifyOfPropertyChange(() => IncidentName);
            _events.BeginPublishOnUIThread(new BindableCollection<Incident>(Incidents));
        }


    }
}

DisplayIncidentView.xaml:

                <ComboBox x:Name = "Incidents"  Height = "40" 
                   BorderBrush = "#FFC7CC00" Foreground = "#DD000000"
                   SelectedItem = "{Binding SelectedIncident, Mode=OneWayToSource}"
                   DisplayMemberPath = "Name"
                   materialDesign:HintAssist.Hint = "Search" IsEditable = "True" Style = "{StaticResource MaterialDesignFloatingHintComboBox}"/>
Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
0
56
1

Ответы 1

Я забыл добавить в конструктор DisplayIncidentViewModel:

_events.Subscribe(this);

Другие вопросы по теме