簡體   English   中英

ItemsSource更改時,ComboBox不會更新

[英]ComboBox does not update when ItemsSource changes

我有一個ComboBox綁定到List<string> 當列表更改時,即使提出了PropertyChanged,ComboBox也不會更改。 調試時,我發現甚至讀取了List屬性。

可以使用以下代碼重現該錯誤:

XAML

<Window x:Class="ComboBoxTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="90" Width="400">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ComboBox ItemsSource="{Binding Source, Mode=OneWay}"/>
        <Button Grid.Column="1" Content="add string" Command="{Binding}" CommandParameter="Add"/>
    </Grid>
</Window>

后面的代碼

using System.Windows;

namespace ComboBoxTest
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new ViewModel();
        }
    }
}

視圖模型

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;

namespace ComboBoxTest
{
    class ViewModel : INotifyPropertyChanged, ICommand
    {
        public ViewModel()
        {
            Source = new List<string>();
            Source.Add("Test1");
            Source.Add("Test2");
            Source.Add("Test3");
        }

        private List<string> _Source;

        public List<string> Source
        {
            get { return _Source; }
            set
            {
                _Source = value;
                OnPropertyChanged("Source");
            }
        }

        private void OnPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event System.EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            if ((string)parameter == "Add")
            {
                Source.Add("New string");
                OnPropertyChanged("Source");
            }
        }
    }
}

為什么ComboBox不更新?

ComboBox不會更新,因為它在檢查列表時看不到任何更改。 引用保持不變,並且不會向ComboBox通知列表內的更改。

重構代碼以使用ObservableCollection而不是List可以解決此問題,因為ObservableCollection實現了INotifyCollectionChanged ,因此有必要向View通知對象內部的更改。

暫無
暫無

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

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