Обновите элементы комбинированного списка из другой ViewModel - PullRequest
0 голосов
/ 19 февраля 2019

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

Я удаляю или добавляю элементы в список в EditIncidentViewModel и использую IEventAggregator для передачи этого списка в Combobox в 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}"/>

1 Ответ

0 голосов
/ 19 февраля 2019

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

_events.Subscribe(this);
...