更改集合时WPF Combobox不会更新

Gan*_*ute 10 c# wpf binding combobox observablecollection

我是WPF的新手.

我正在尝试将字符串集合绑定到组合框.

public ObservableCollection<string> ListString {get; set;}
Run Code Online (Sandbox Code Playgroud)

绑定和datacontext设置如下

<Window 
        x:Class="Assignment2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:validators="clr-namespace:Assignment2"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}, Path=.}">
    <Grid>
        <ComboBox  Height="23" HorizontalAlignment="Left" Margin="109,103,0,0" Name="StringComboBox" VerticalAlignment="Top" Width="120" SelectionChanged="StringComboBox_SelectionChanged">
            <ComboBox.ItemsSource>
                <Binding Path="ListString" BindsDirectlyToSource="True" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"></Binding>
            </ComboBox.ItemsSource>
        </ComboBox>
Run Code Online (Sandbox Code Playgroud)

我发现这种情况正在发生,因为集合正在更新.如果我写

public MainWindow()
        {

            InputString = "";
            ListString = new ObservableCollection<string>();
            ListString.Add("AAA");
            ListString.Add("BBB");
            ListString.Add("CCC");
          InitializeComponent();

        }
Run Code Online (Sandbox Code Playgroud)

它确实有效,但是如果我InitializeComponent()在第一行上面移动如下,则不起作用.

  public MainWindow()
            {
               InitializeComponent();
                InputString = "";
                ListString = new ObservableCollection<string>();
                ListString.Add("AAA");
                ListString.Add("BBB");
                ListString.Add("CCC");                
            }
Run Code Online (Sandbox Code Playgroud)

我该怎么办??

Gan*_*ute 14

解决了这个问题.实现了INotifyPropertyChanged,如下所示

public partial class MainWindow : Window, INotifyPropertyChanged
Run Code Online (Sandbox Code Playgroud)

修改了访问器如下

    private ObservableCollection<string> listString;
    public ObservableCollection<string> ListString 
    {
        get
        {
            return listString;
        }
        set
        {
            listString = value;
            NotifyPropertyChanged("ListString"); // method implemented below
        }
    }
Run Code Online (Sandbox Code Playgroud)

并添加了以下事件和方法来引发事件

public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string name)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this,new PropertyChangedEventArgs(name));
    }
}
Run Code Online (Sandbox Code Playgroud)

它有效B)