单击按钮时更新另一个ViewModel

时间:2016-06-21 12:55:05

标签: c# wpf

我在点击按钮时尝试更新另一个ViewModel。那个Viewmodel已经有一个更新自己的ViewModel的按钮,但是我希望在另一个viewModel上具有完全相同的功能

这是我的代码:

OlyckorViewModel(我想要更新的视图以及已经有更新它的按钮) SearchActiveInvestigationsCommand是更新它的按钮绑定

public class OlyckorViewModel : NotificationObject
    {
        private readonly ISosServiceDelegate _sosService;
        private readonly IDialogService _dialogService;
        private string _searchConditionDiarienummer;
        private string _searchConditionFartygsnamn;
        private string _searchConditionRegisterbeteckning;
        private int? _searchConditionIMONummer;
        private DateTime? _searchConditionHaendelseDatum;
        private string _searchConditionOlyckshaendelsetypKod;
        private bool _isSearching;
        private bool _isSearchExpanded = true;
        private ObservableCollection<SosListOlycka> _olyckor;
        private SosListOlycka _selectedOlycka;
        private string _statusText;

        public OlyckorViewModel(ISosServiceDelegate sosService, ILoggerFacade logger, IDialogService dialogServce)
        {
            logger.Log("Initializing OlyckorViewModel", Category.Debug, Priority.Low);

            _sosService = sosService;
            _dialogService = dialogServce;

            SearchCommand = new DelegateCommand(ExecuteSearch, CanExecuteSearch);
            SearchActiveInvestigationsCommand = new DelegateCommand(ExecuteSearchActiveInvestigations, CanExecuteSearchActiveInvestigations);
            OpenCommand = new DelegateCommand(ExecuteOpen, CanExecuteOpen);
            DeleteCommand = new DelegateCommand(ExecuteDelete, CanExecuteDelete);
            CreatePdfReportCommand = new DelegateCommand(ExecuteCreatePdfReport, CanExecuteCreatePdfReport);
        }


 private void ExecuteSearch()
        {
            if (IsSearching)
                return;

            IsSearching = true;
            StatusText = "Söker olyckor...";

            var criteria = new SosOlyckaSearchCriteria();
            criteria.Diarienummer = SearchConditionDiarienummer;
            criteria.Fartygsnamn = SearchConditionFartygsnamn;
            criteria.Registerbeteckning = SearchConditionRegisterbeteckning;
            criteria.IMONummer = SearchConditionIMONummer;
            criteria.HaendelseDatum = SearchConditionHaendelseDatum;
            criteria.OlyckshaendelseTypKod = SearchConditionOlyckshaendelsetypKod;

            _sosService.SearchOlyckor(
                criteria,
                olyckor =>
                {
                    HandleResultFromSearch(olyckor);
                },
                exception =>
                {
                    IsSearching = false;
                    StatusText = "Misslyckades att söka olyckor";
                    DialogHelper.ShowException(exception);
                }
            );
        }

private void HandleResultFromSearch(SosSearchResult<SosListOlycka> olyckor)
        {
            IsSearching = false;
            IsSearchExpanded = false;
            Olyckor = new ObservableCollection<SosListOlycka>(olyckor.Items);

            StatusText = Olyckor.Count + " " + (Olyckor.Count == 1 ? "olycka." : "olyckor.");

            if (olyckor.IsResultTruncated)
            {
                var statusTextResultTruncated = "Resultatet var för stort (" + olyckor.OriginalNumberOfHits + " olyckor) och trunkerades på servern.";
                StatusText += " " + statusTextResultTruncated;
            }

            // if search result only contains a single item, it should be opened
            if (Olyckor.Count == 1)
                DialogHelper.OpenOlyckaDialog(Olyckor[0].OlyckaId);
        }

OlyckaViewModel(应该有一个保存按钮来更新上面的视图模型的viewModel) SaveCommand是我要更新的按钮绑定,如上面的按钮

 public class OlyckaViewModel : DialogWindowViewModel
        {
            private readonly ISosServiceDelegate _sosService;
            private readonly Repository _repository;
            private readonly IDialogService _dialogService;
            private readonly IInteractionService _interactionService;
            private readonly FroCodesViewModel _froCodesViewModel;
            private SosOlycka _model;
            private SosOlycksorsak _selectedOlycksorsak;
            private SosOlycksorsak _selectedHuvudorsak;
            private SosStegIOlycksfoerlopp _selectedStegIOlycksfoerlopp;
            private SosStegIOlycksfoerlopp _selectedInledandeSteg;
            private SosOlycka _selectedOtherOlycka;
            private OlyckorViewModel _olyckorlist;

            private readonly ObservableCollection<CheckBoxListItemViewModel<TrsFartygsunderkategori>> _fartygsunderkategorier = new ObservableCollection<CheckBoxListItemViewModel<TrsFartygsunderkategori>>();
            private int? _olycksrapportIdToHaemtmarkeraWhenSaving;
            private ObservableCollection<SosListOlycka> _olyckor;
            private SosListOlycka _selectedOlycka;
            private bool _isSearching;
            private bool _isSearchExpanded = true;


            private readonly List<KnownValue> _oestEllerVaest = new List<KnownValue>()
        {
            new KnownValue("Välj", null),
            new KnownValue("E", "E"),
            new KnownValue("W", "W")
        };

            private readonly List<KnownValue> _nordEllerSyd = new List<KnownValue>()
        {
            new KnownValue("Välj", null),
            new KnownValue("N", "N"),
            new KnownValue("S", "S")
        };

            public OlyckaViewModel(ISosServiceDelegate sosService, Repository repository, IDialogService dialogService, IInteractionService interactionService)
            {
                _sosService = sosService;
                _repository = repository;
                _dialogService = dialogService;
                _interactionService = interactionService;
                _froCodesViewModel = new FroCodesViewModel(ServiceLocator.Current.GetInstance<ISitsServiceDelegate>());



                SaveCommand = new DelegateCommand(ExecuteSave);
                ReloadCommand = new DelegateCommand(ExecuteReload, CanExecuteIfExistingOlycka);
                CloseCommand = new DelegateCommand(Close);
                DeleteCommand = new DelegateCommand(ExecuteDelete, CanExecuteIfExistingOlycka);
                AvslutaUtredningCommand = new DelegateCommand(ExecuteAvslutaUtredning, CanExecuteIfExistingOlycka);
                CreatePdfReportCommand = new DelegateCommand(ExecuteCreatePdfReport, CanExecuteIfExistingOlycka);
                AddOlycksorsakCommand = new DelegateCommand(ExecuteAddOlycksorsak);
                RemoveOlycksorsakCommand = new DelegateCommand(ExecuteRemoveOlycksorsak, CanExecuteRemoveOlycksorsak);
                AddStegIOlycksfoerloppCommand = new DelegateCommand(ExecuteAddStegIOlycksfoerlopp);
                RemoveStegIOlycksfoerloppCommand = new DelegateCommand(ExecuteRemoveStegIOlycksfoerlopp, CanExecuteRemoveStegIOlycksfoerlopp);
                FetchFartygsinformationFromSitsCommand = new DelegateCommand(ExecuteFetchFartygsinformationFromSits);
                NewOlyckaFromHaendelseCommand = new DelegateCommand(ExecuteNewOlyckaFromHaendelse);
                OpenOtherOlyckaCommand = new DelegateCommand(ExecuteOpenOtherOlycka, CanExecuteOpenOtherOlycka);
                MoveOlyckaToNewHaendelseCommand = new DelegateCommand(ExecuteMoveOlyckaToNewHaendelse);
                MoveOlyckaToOtherHaendelseCommand = new DelegateCommand(ExecuteMoveOlyckaToOtherHaendelse);
                MarkSelectedOlycksorsakAsHuvudorsakCommand = new DelegateCommand(ExecuteMarkSelectedOlycksorsakAsHuvudorsak);
                MarkSelectedStegIOlycksfoerloppAsInledandeStegCommand = new DelegateCommand(MarkSelectedStegIOlycksfoerloppAsInledandeSteg);
                SearchActiveInvestigationsCommand = new DelegateCommand(ExecuteSearchActiveInvestigations, CanExecuteSearchActiveInvestigations);
            }



            public DelegateCommand SaveCommand { get; private set; }
            public DelegateCommand ReloadCommand { get; private set; }
            public DelegateCommand CloseCommand { get; private set; }
            public DelegateCommand DeleteCommand { get; private set; }
            public DelegateCommand AvslutaUtredningCommand { get; private set; }
            public DelegateCommand CreatePdfReportCommand { get; private set; }
            public DelegateCommand AddOlycksorsakCommand { get; private set; }
            public DelegateCommand RemoveOlycksorsakCommand { get; private set; }
            public DelegateCommand AddStegIOlycksfoerloppCommand { get; private set; }
            public DelegateCommand RemoveStegIOlycksfoerloppCommand { get; private set; }
            public DelegateCommand FetchFartygsinformationFromSitsCommand { get; private set; }
            public DelegateCommand NewOlyckaFromHaendelseCommand { get; private set; }
            public DelegateCommand OpenOtherOlyckaCommand { get; private set; }
            public DelegateCommand MoveOlyckaToNewHaendelseCommand { get; private set; }
            public DelegateCommand MoveOlyckaToOtherHaendelseCommand { get; private set; }
            public DelegateCommand MarkSelectedOlycksorsakAsHuvudorsakCommand { get; private set; }
            public DelegateCommand MarkSelectedStegIOlycksfoerloppAsInledandeStegCommand { get; private set; }
            public DelegateCommand SearchActiveInvestigationsCommand { get; private set; }
            public DelegateCommand SearchCommand { get; private set; }

            public FroCodesViewModel FroCodesViewModel { get { return _froCodesViewModel; } }

            public OlyckorViewModel OlyckorViewModel { get { return _olyckorlist; } }
            public SosOlycka Model
            {
                get { return _model; }
                private set
                {
                    if (value != _model)
                    {
                        _model = value;
                        RaisePropertyChanged(() => Model);
                        RaisePropertyChanged(() => IsExistingOlycka);
                        RaiseCanExecuteChangedForOlyckaCommands();

                        LoadDescriptionsForFroCodes();

                        SynchronizeFromModel();
                    }
                }
            }



private void ExecuteSave()
            {
                if (IsBusy)
                    throw new InvalidOperationException("Cannot save olycka, is already busy");

                SynchronizeToModel();

                // Validate ad-acta
                List<string> missingAdActaFields = null;
                if (Model.MyndighetensUtredningAvslutad.HasValue)
                {
                    missingAdActaFields = DataHelper.ValidateAdActa(Model);
                }

                // Validate skrovskada
                List<string> missingSkrovskadaFields = null;
                if (Model.SosFartygsskada.Skrovskada == "J")
                {
                    missingSkrovskadaFields = DataHelper.ValidateSkrovskada(Model);
                }

                if ((missingAdActaFields != null && missingAdActaFields.Count > 0)
                    || (missingSkrovskadaFields != null && missingSkrovskadaFields.Count > 0))
                {
                    // Bring up window of missing fields (or update if already open)
                    var vm = _dialogService.GetOpenDialogs().OfType<MissingFieldsViewModel>().FirstOrDefault();
                    if (vm != null)
                    {
                        vm.AdActaFields = missingAdActaFields;
                        vm.SkrovskadaFields = missingSkrovskadaFields;
                        _dialogService.Activate(vm);
                    }
                    else
                    {
                        vm = ServiceLocator.Current.GetInstance<MissingFieldsViewModel>();
                        vm.AdActaFields = missingAdActaFields;
                        vm.SkrovskadaFields = missingSkrovskadaFields;
                        _dialogService.Show(vm);
                    }



                    //




                    // Cancel save operation
                    return;
                }
                else
                {
                    // Close window with missing fields if open)
                    var vm = _dialogService.GetOpenDialogs().OfType<MissingFieldsViewModel>().FirstOrDefault();
                    if (vm != null)
                    {
                        vm.Close();
                    }
                }

                SetBusy("Sparar ändringar...");

                _sosService.SaveOlycka(
                    Model,
                    result =>
                    {
                        // load olycka using the id returned from save method (useful if olycka was new / not previously persisted)
                        ResetBusy();

                        if (IsGoingToHaemtmarkeraWhenSaving)
                        {
                            SetBusy("Markerar olycksrapport som hämtad...");

                            var rosService = ServiceLocator.Current.GetInstance<IRosServiceDelegate>();
                            rosService.HaemtmarkeraOlycksrapport(
                                OlycksrapportIdToHaemtmarkeraWhenSaving.Value,
                                result,
                                () =>
                                {
                                    ResetBusy();
                                    OlycksrapportIdToHaemtmarkeraWhenSaving = null;
                                    LoadOlycka(result);
                                },
                                haemtmarkeraException =>
                                {
                                    ResetBusy();
                                    DialogHelper.ShowException(haemtmarkeraException);
                                }
                            );
                        }
                        else
                        {
                            LoadOlycka(result);
                        }
                    },
                    exception =>
                    {
                        ResetBusy();
                        DialogHelper.ShowException(exception);
                    }
                );

                ExecuteSearchActiveInvestigations();
            }

我知道很多代码,我只是想确保不要错过任何内容。

我尝试将相同的代码从已经工作的按钮复制到我想要工作的按钮,但它没有工作,我怀疑它是因为我没有告诉它更新另一个视图,而不是自己。我可能是错的。

我感谢任何帮助,

2 个答案:

答案 0 :(得分:1)

使用所需参数从OlyckaViewModel引发事件,并在OlyckorViewModel中进行订阅。 使代码在SearchActiveInvestigationsCommand中通用,并从订阅的事件方法调用相同的函数。

答案 1 :(得分:0)

  

我在点击按钮时尝试更新另一个ViewModel。

另一个 viewmodel中,将更新代码集中到一个公共方法中。

  1. 在应用程序代码中,对相关VM进行静态引用。
  2. 另一个 viewmodel将自己的引用作为静态引用添加到应用程序中。
  3. 将更新代码集中到该VM上的公共方法中。该方法可能有多个变量,必须通过这些变量从任何外部虚拟机进行任何更新或从视图中单击按钮。
  4. 点击按钮,从中获取全局app(请参阅Application.Current Property (System.Windows))并找到对相关VM的引用。然后调用更新方法。