簡體   English   中英

Web Service更新后,組合框中的“選定項目”未更改其值

[英]Selected Item in combobox is not changing its value after Web Service update

我有一個WPF用戶控件,其中包含一個組合框:

<UserControl
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" x:Class="Hartville.SalesScriptApplication.Views.SalesScriptEditorGroups" 
             mc:Ignorable="d" 
         xmlns:events="http://schemas.microsoft.com/expression/2010/interactivity"
         xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
             xmlns:hartvm="clr-namespace:Hartville.SalesScript.ViewModels;assembly=Hartville.SalesScript.ViewModels"
             d:DesignHeight="106" d:DesignWidth="909" Background="#FFF3EDED">
    <UserControl.Resources>
        <ResourceDictionary>
            <hartvm:ViewLocator x:Key="HartvilleLocator" d:IsDataSource="True" />
        </ResourceDictionary>
    </UserControl.Resources>
    <UserControl.DataContext>
        <Binding Source="{StaticResource HartvilleLocator}" Path="ScriptEditorGroups" />
    </UserControl.DataContext>
    <Border>
        <Grid Margin="5,10,0,20">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <StackPanel Orientation="Horizontal" Margin="0,10,0,20">
                <TextBlock TextWrapping="Wrap" Text="Selected Script Group:"/>
                <ComboBox Width="250" Margin="10,0,0,0" HorizontalAlignment="Left" ItemsSource="{Binding ScriptGroups}" SelectedItem="{Binding SelectedScriptGroup}" 
                    DisplayMemberPath="Name" >
                    <events:Interaction.Triggers>
                        <events:EventTrigger EventName="SelectionChanged">
                            <cmd:EventToCommand Command="{Binding ScriptGroupSelectedCommand}" PassEventArgsToCommand="False" />
                        </events:EventTrigger>
                    </events:Interaction.Triggers>              
                </ComboBox>
            </StackPanel>
    </Border>
</UserControl>

注意:我們正在使用MVVM light框架。 您看到的視圖定位器只是一個實例化視圖模型的類,您將在數據上下文部分中看到該視圖模型。

從組合框中選擇某項並單擊“編輯”按鈕時,用戶可以更新名稱並保存。 但是,當用戶單擊“保存”時,您可以在組合框中看到更改的選擇,但是所選項目仍包含原始名稱。 因此,例如,我從組合框中選擇選項“ Hello World”。 我將名稱更改為“ FOOBAR”,然后單擊“保存”。 我更新了代碼中的所選項目(並且我可以看到該屬性正在更改)。 當我選中組合框時,我看到“ FOOBAR”,但所選值仍然顯示“ Hello World”。 而且,“ Hello World”在組合框中不再存在(顯然是因為我剛剛對其進行了更新。

這是視圖模型的代碼:

using System.Windows.Input;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight.Command;
using Hartville.Common.Controls.ViewModels;
using Hartville.Common.Controls.ViewModels.Validation;
using Hartville.SalesScript.ViewModels.Messages;
using Hartville.Values.Sales;
using System.Linq;

namespace Hartville.SalesScript.ViewModels.Scripts
{
    public class ScriptEditorGroups: CommonViewModelBase
    {
        private ObservableCollection<ScriptHeader> _scriptGroups;
        private ObservableCollection<Script> _scripts; 
        private ScriptHeader _selectedScriptGroup;
        private Script _selectedScript;
        private bool _isScriptGroupActive;
        private string _groupName;
        private bool _shouldEnableScriptGroup;
        private bool _shouldShowGroupEditPanel;
        private bool _shouldUseDefaultScript;
        private bool _shouldShowScriptSelection;

        public ICommand EditSelectedCommand { get; set; }
        public ICommand NewGroupCommand { get; set; }
        public ICommand SaveCommand { get; set; }
        public ICommand ScriptGroupSelectedCommand { get; set; }

        public ObservableCollection<ScriptHeader> ScriptGroups
        {
            get { return _scriptGroups; }
            set { SetPropertyValue(ref _scriptGroups, value); }
        }

        public ObservableCollection<Script> Scripts
        {
            get { return _scripts; }
            set { SetPropertyValue(ref _scripts, value); }
        }

        public ScriptHeader SelectedScriptGroup
        {
            get { return _selectedScriptGroup; }
            set { SetPropertyValue(ref _selectedScriptGroup, value ); }
        }

        public Script SelectedScript
        {
            get { return _selectedScript; }
            set { SetPropertyValue(ref _selectedScript, value); }
        }

        public bool IsScriptGroupActive
        {
            get { return _isScriptGroupActive; }
            set { SetStructPropertyValue(ref _isScriptGroupActive, value); }
        }

        public string GroupName
        {
            get { return _groupName; }
            set { SetStructPropertyValue(ref _groupName, value); }
        }

        public bool ShouldEnableScriptGroup
        {
            get { return _shouldEnableScriptGroup; }
            set { SetStructPropertyValue(ref _shouldEnableScriptGroup, value); }
        }

        public bool ShouldShowGroupEditPanel
        {
            get { return _shouldShowGroupEditPanel; }
            set { SetStructPropertyValue(ref _shouldShowGroupEditPanel, value); }
        }

        public bool ShouldUseDefaultScript
        {
            get { return _shouldUseDefaultScript; }
            set { SetStructPropertyValue(ref _shouldUseDefaultScript, value); }
        }

        public bool ShouldShowScriptSelection
        {
            get { return _shouldShowScriptSelection; }
            set { SetStructPropertyValue(ref _shouldShowScriptSelection, value); }
        }

        public bool IsEdit { get; set; }
        public bool IsNew { get; set; }

        protected override void RegisterForMessages()
        {
            MessengerService.Register<BeginSalesScriptEditorMessage>(OnBeginSalesScriptEditor);

            EditSelectedCommand = new RelayCommand(OnEdit);
            NewGroupCommand = new RelayCommand(OnNewGroup);
            SaveCommand = new RelayCommand(OnSave);
            ScriptGroupSelectedCommand = new RelayCommand(OnScriptGroupSelected);
        }

        private void OnBeginSalesScriptEditor(BeginSalesScriptEditorMessage message)
        {
            ScriptGroups = new ObservableCollection<ScriptHeader>(SalesService.GetAllScriptHeader());
            Scripts = new ObservableCollection<Script>(SalesScriptCache.Scripts);

            ShouldEnableScriptGroup = false;
            ShouldShowGroupEditPanel = false;
            ShouldShowScriptSelection = false;
            IsEdit = false;
            IsNew = false;
        }

        private void OnEdit()
        {
            if(SelectedScriptGroup == null) return;

            IsEdit = true;
            ShouldShowGroupEditPanel = true;
            ShouldShowScriptSelection = true;
            GroupName = SelectedScriptGroup.Name;
            SelectedScript = SalesScriptCache.Scripts.FirstOrDefault(s => s.ScriptId == SelectedScriptGroup.StartScriptId);
        }

        private void OnNewGroup()
        {
            IsNew = true;
            GroupName = string.Empty;
            ShouldShowGroupEditPanel = true;
            ShouldShowScriptSelection = false;
        }

        private void OnSave()
        {
            ThreadManagement.ExecuteInSeparateThread(ProcessScriptUpdate);
        }

        private void OnScriptGroupSelected()
        {
            if(SelectedScriptGroup == null) return;

            MessengerService.Send(ScriptHeaderSelectedMessage.Create(SelectedScriptGroup));
            ShouldEnableScriptGroup = true;
        }

        protected override void SetDesignTimeInfo(){}

        protected void ResetValues()
        {
            ShouldEnableScriptGroup = false;
            ShouldShowGroupEditPanel = false;
            IsScriptGroupActive = false;
            IsEdit = false;
            IsNew = false;
            ShouldShowScriptSelection = false;
        }

        private int CreateNewScriptGroup()
        {
            var scriptHeader = new ScriptHeader
                                   {
                                       Name = GroupName,
                                       IsActive = IsScriptGroupActive
                                   };

            MessengerService.Send(ScriptHeaderSelectedMessage.Create(scriptHeader));
            return SalesService.ScriptHeaderInsertUpdate(scriptHeader);
        }

        private int EditExistingScriptGroup()
        {
            if(SelectedScriptGroup == null) return 0;

            var scriptHeader = new ScriptHeader
                                   {
                                       Name = GroupName,
                                       IsActive = IsScriptGroupActive,
                                       ScriptHeaderId = SelectedScriptGroup.ScriptHeaderId,
                                       StartScriptId = SelectedScript.ScriptId
                                   };

            MessengerService.Send(ScriptHeaderSelectedMessage.Create(scriptHeader));
            return SalesService.ScriptHeaderInsertUpdate(scriptHeader);
        }

        private void ProcessScriptUpdate()
        {
            var returnId = 0;

            if (IsNew)
                returnId = CreateNewScriptGroup();
            else if (IsEdit)
                returnId = EditExistingScriptGroup();

            ScriptGroups = new ObservableCollection<ScriptHeader>(SalesService.GetAllScriptHeader());
            SelectedScriptGroup = ScriptGroups.FirstOrDefault(h => h.ScriptHeaderId == returnId);

            ResetValues();
        }
    }
}

如何解決此問題?

編輯:

這是SetPropertyValue方法,該方法調用notify:

public virtual void SetPropertyValue<T>(ref T currentValue, T newValue, Action<T> extraFunction = null, Action voidAfterSetAction = null) where T : class
        {
            if (currentValue == newValue) return;

            currentValue = newValue;

            PropertyHasChanged();

            if (extraFunction != null) extraFunction(newValue);

            if (voidAfterSetAction != null) voidAfterSetAction();
        }

編輯:

這是保存屬性更改代碼的整個基類:

using System;
using System.ComponentModel;
using System.Diagnostics;
using GalaSoft.MvvmLight;
using Hartville.Common.Controls.Messaging;
using Hartville.Common.Controls.Modules;
using Hartville.Common.Controls.ViewModels.Validation;
using Hartville.Common.Controls.WebServices;
using Hartville.Common.Threading;

namespace Hartville.Common.Controls.ViewModels
{
    public abstract class CommonViewModelBase : ViewModelBase, IDataErrorInfo
    {


        public string this[string columnName]
        {
            get
            {
                var validationReturn = ValidationManager.Validate(columnName);

                OnValidationComplete();

                return validationReturn;
            }
        }

        public string Error
        {
            get { return null; }
        }

        protected CommonViewModelBase()
        {
            ValidationManager = ValidationManager.Start(this);

            RegisterForMessages();

            if (IsInDesignMode) SetDesignTimeInfo();
        }

        public virtual void Reset()
        {
            IsProcessing = false;
        }

        public virtual void OnValidationComplete()
        {
        }

        public virtual void SetPropertyValue<T>(ref T currentValue, T newValue, Action<T> extraFunction = null, Action voidAfterSetAction = null) where T : class
        {
            if (currentValue == newValue) return;

            currentValue = newValue;

            PropertyHasChanged();

            if (extraFunction != null) extraFunction(newValue);

            if (voidAfterSetAction != null) voidAfterSetAction();
        }

        public virtual void SetPropertyValue<T>(ref T currentValue, T newValue, Action extraFunction) where T : class
        {
            if (currentValue == newValue) return;

            currentValue = newValue;

            PropertyHasChanged();

            if (extraFunction != null) extraFunction();
        }

        public virtual void SetStructPropertyValue<T>(ref T currentValue, T newValue, Action<T> extraFunction = null, Action voidActionAfterSetAction = null)
        {
            currentValue = newValue;

            PropertyHasChanged();

            if (extraFunction != null) extraFunction(newValue);

            if (voidActionAfterSetAction != null) voidActionAfterSetAction();
        }

        public virtual void SetStructPropertyValue<T>(ref T currentValue, T newValue, Action extraFunction)
        {
            currentValue = newValue;

            PropertyHasChanged();

            if (extraFunction != null) extraFunction();
        }

        public virtual void SetValue<T>(ref T currentValue, T newValue, Action<T> voidOldValueAction = null, Action voidAfterSetAction = null) where T : class
        {
            var oldVal = currentValue;

            if (currentValue == newValue) return;

            currentValue = newValue;

            PropertyHasChanged();

            if (voidOldValueAction != null) voidOldValueAction(oldVal);

            if (voidAfterSetAction != null) voidAfterSetAction();
        }

        protected abstract void RegisterForMessages();
        protected abstract void SetDesignTimeInfo();

        protected void SendModalCloseMessage()
        {
            MessengerService.Send(ModalCommandMessage.Create(ModalOptions.Close));
        }

        protected void SendModalOpenMessage(ModalName windowName, Guid? customID = null)
        {
            MessengerService.Send(ModalCommandMessage.Create(ModalOptions.Open, windowName, customID));
        }

        private void PropertyHasChanged()
        {
            var currentFrame = 2;

            var frame = new StackFrame(currentFrame);

            var propertyName = string.Empty;

            if (frame.GetMethod().Name.Length > 4) propertyName = GetPropertyName(frame);

            while (!frame.GetMethod().Name.StartsWith("set_"))
            {
                currentFrame++;

                frame = new StackFrame(currentFrame);

                if (frame.GetMethod().Name.Length > 4) propertyName = GetPropertyName(frame);
            }

            RaisePropertyChanged(propertyName);
        }

        private static string GetPropertyName(StackFrame frame)
        {
            return frame.GetMethod().Name.Substring(4);
        }
    }
}

您需要實現iNotifyPropertyChanged並在其中調用PropertyChanged

    public ScriptHeader SelectedScriptGroup 
    { 
        set { SetPropertyValue(ref _selectedScriptGroup, value ); } 
    } 

除了Blam已經提到的內容之外,您還必須在CommonViewModelBase或當前視圖模型中實現INotifyPropertyChanged接口。 並且,應該在將數據上下文分配給視圖之后,為要更改其值的所有屬性設置器調用PropertyChanged方法。

public ScriptHeader ScriptGroups
{ 
    set { SetPropertyValue(ref _selectedScriptGroup, value ); 
          PropertyChanged("SelectedScriptGroup ");
        } 
}

public ScriptHeader SelectedScriptGroup 
{ 
    set { SetPropertyValue(ref _selectedScriptGroup, value ); 
          PropertyChanged("SelectedScriptGroup");
        } 
}

否則,您的視圖無法知道控件綁定到的屬性值已更改。 有關實施,請參閱屬性更改實施

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM