0

在我的项目中,我的 selectedvalue 在 vi​​ewmodel 中正确设置,但我的视图未设置其 selectedvalue

在xml代码中:

 <ComboBox ItemsSource="{Binding AllValues}" SelectedValue="{Binding SelectedValue,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Width="150" Margin="5,0,0,0">

在视图模型中:

public Model SelectedValue
        {
            get
            {
                return _model.Value;
            }
            set
            {
                 _model.Value = value;
                if (CVSCollection.View != null)
                    CVSCollection.View.Refresh();
                RaisePropertyChanged("SelectedValue");
            }
        }
4

2 回答 2

0

尝试将 aICollectionView与 结合使用IsSynchronizedWithCurrentItem。ICollectionView 负责所有与组合框相关的操作。您还可以设置当前选定的项目。

xml:

  <ComboBox ItemsSource="{Binding AllValues}"  
                  IsSynchronizedWithCurrentItem="True"
                  Width="150" 
                  Margin="5,0,0,0"/>  

视图模型

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;

namespace ComboBoxBinding
{
    public class ViewModelSpike : INotifyPropertyChanged
    {
        private ObservableCollection<Model> _allValues = new ObservableCollection<Model>();
        private Model _selectedValue;

        public ObservableCollection<Model> AllValues
        {
            get { return _allValues; }
            set { _allValues = value; OnPropertyChanged("AllValues");}
        }

        public Model SelectedValue
        {
            get { return _selectedValue; }
            set { _selectedValue = value; OnPropertyChanged("SelectedValue");}
        }

        public ICollectionView ModelsView { get; private set; }

        public ViewModelSpike()
        {
            //First init / load AllValues here...

            ModelsView = CollectionViewSource.GetDefaultView(AllValues);
            ModelsView.CurrentChanged += OnCurrentModelChanged;

            //You can also set the current selected item / initial selected item
            //ModelsView.MoveCurrentTo(DesiredModel from AllValues)
        }

        private void OnCurrentModelChanged(object sender, EventArgs e)
        {
            if (ModelsView.CurrentItem == null) return;
            var selectedValue = ModelsView.CurrentItem as Model;

            if (selectedValue == null) return;

            SelectedValue = selectedValue;

            if (CVSCollection.View != null) CVSCollection.View.Refresh();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
于 2012-11-01T07:23:00.940 回答
0

我已经自己解决了,因为我已将 selectedvalue 的局部变量设置为 _selectedValue 并在构造函数中设置了 _selectedValue..

于 2012-11-07T07:43:34.860 回答