当ObservableCollection在另一个视图中被修改时,ComboBox不更新

本文关键字:ComboBox 更新 修改 ObservableCollection 另一个 视图 | 更新日期: 2023-09-27 18:13:07

我正在做一个小的MVVM WPF项目用于实践目的,我有两个窗口,每个窗口有一个视图,一个用于显示员工(MainWindow),一个用于添加员工(AddPersonWindow)。

在我的主窗口中,有一个绑定到ObservableCollection的组合框,我可以从我的MainWindow中的按钮打开AddPersonWindow。但是,如果我通过单击保存按钮并执行AddPerson()函数将雇员添加到AddPersonWindow的ObservableCollection中,则主窗口中的ComboBox不会更新。如果我执行与MainWindow相同的AddPerson()函数,则一切正常,ComboBox显示新条目。我遗漏了什么?

代码:

Person.cs

class Person
{
    public string Surname { get; set; }
    public string Name { get; set; }
    public string Street { get; set; }
    public string HouseNumber { get; set; }
    public string PostalCode { get; set; }
    public string City { get; set; }
    public string PhoneAreaCode { get; set; }
    public string PhoneNumber { get; set; }
    public string Email { get; set; }
    public string FullName { get { return String.Format("{0}, {1}", Name, Surname); } }
}

PersonViewModel.cs

class PersonViewModel : INotifyPropertyChanged
{
    public CommandHandler ButtonClick { get; set; }
    public PersonViewModel()
    {
        CreatePerson();
    }       
    //Combobox SelectedItem
    private Person _selectedPerson;
    public Person SelectedPerson
    {
        get { return _selectedPerson; }
        set
        {
            _selectedPerson = value;
            OnPropertyChanged("SelectedPerson");
        }
    }      

    public ObservableCollection<Person> PersonList { get; set; } = new ObservableCollection<Person>();

    public void CreatePerson()
    {     

        foreach (string line in File.ReadLines(@"C:'some_file.csv", Encoding.GetEncoding("iso-8859-1")))
        {
            string[] substrings = line.Split(',');
            Person person = new Person {
                Surname = substrings[0],
                Name = substrings[1],
                Street = substrings[2],
                HouseNumber = substrings[3],
                PostalCode = substrings[4],
                City = substrings[5],
                PhoneAreaCode = substrings[6],
                PhoneNumber = substrings[7],
                Email = substrings[8] };
                PersonList.Add(person);
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

}

AddPersonViewModel.cs

class AddPersonViewModel : PersonViewModel
{

    public AddPersonViewModel()
    {
        ButtonClick = new CommandHandler(AddPerson);
    }
    public string EnteredSurname { get; set; }
    public string EnteredName { get; set; }
    public string EnteredStreet { get; set; }
    public string EnteredHouseNumber { get; set; }
    public string EnteredPostalCode { get; set; }
    public string EnteredCity { get; set; }
    public string EnteredPhoneAreaCode { get; set; }
    public string EnteredPhoneNumber { get; set; }
    public string EnteredEmail { get; set; }

    public void AddPerson()
    {

        Person person = new Person
        {
            Surname = EnteredSurname,
            Name = EnteredName,
            Street = EnteredStreet,
            HouseNumber = EnteredHouseNumber,
            PostalCode = EnteredPostalCode,
            City = EnteredCity,
            PhoneAreaCode = EnteredPhoneAreaCode,
            PhoneNumber = EnteredPhoneNumber,
            Email = EnteredEmail
        };
        PersonList.Add(person);
    }
}

CommandHandler.cs

class CommandHandler : ICommand
{
    Action ExecuteHandler;
    public CommandHandler(Action executeHandler)
    {            
        ExecuteHandler = executeHandler;
    }
    public event EventHandler CanExecuteChanged;
    public bool CanExecute(object parameter)
    {
        return true;
    }
    public void Execute(object parameter)
    {
        ExecuteHandler();
    }
}

MainWindow.xaml.cs:

 public MainWindow()
    {
        InitializeComponent();
        DataContext = new PersonViewModel();
    }

AddPersonWindow.xaml.cs:

 public AddPersonWindow()
    {
        InitializeComponent();
        DataContext = new AddPersonViewModel();
    }

ComboBox in MainWindow.xaml:

<ComboBox Width="325" HorizontalAlignment="Left" Margin="7" Grid.Column="1" ItemsSource="{Binding PersonList}" DisplayMemberPath="FullName" SelectedItem="{Binding SelectedPerson}" IsTextSearchEnabled="True" TextSearch.TextPath="FullName" IsEditable="True" />

AddPersonWindow.xaml:

中的按钮
<Button Width="100" Height="30" Margin="15" Grid.Row="3" Grid.Column="2" HorizontalAlignment="Right" IsEnabled="True" Command="{Binding ButtonClick}">Speichern</Button>

当ObservableCollection在另一个视图中被修改时,ComboBox不更新

我没有设法在两个视图模型之间共享一个PersonList实例,所以我决定直接在AddPersonViewModel中编辑底层CSV文件:

 class AddPersonViewModel
{
    public CommandHandler ButtonClick { get; set; }

    public AddPersonViewModel()
    {
        ButtonClick = new CommandHandler(AddPerson);
    }
    public string EnteredSurname { get; set; }
    public string EnteredName { get; set; }
    public string EnteredStreet { get; set; }
    public string EnteredHouseNumber { get; set; }
    public string EnteredPostalCode { get; set; }
    public string EnteredCity { get; set; }
    public string EnteredPhoneAreaCode { get; set; }
    public string EnteredPhoneNumber { get; set; }
    public string EnteredEmail { get; set; }

    void AddPerson()
    {
        File.AppendAllText(@"C:'some_file.csv", "'r'n" + 
            EnteredSurname + "," +
            EnteredName + "," +
            EnteredStreet + "," +
            EnteredHouseNumber + "," +
            EnteredPostalCode + "," +
            EnteredCity + "," +
            EnteredPhoneAreaCode + "," +
            EnteredPhoneNumber + "," +
            EnteredEmail,
            Encoding.GetEncoding("iso-8859-1")
            );
    }
}
}

为了在另一个视图中添加人员后刷新PersonViewModel类视图中的ComboBox,我实现了一个可以通过单击按钮执行的方法。为此,我使用以下方法:

public void RefreshPersons()
    {
        PersonList.Clear();
        foreach (string line in File.ReadLines(@"C:'Users'c.philipp'Downloads'adressbuch.csv", Encoding.GetEncoding("iso-8859-1")))
        {
            string[] substrings = line.Split(',');
            Person person = new Person
            {
                Surname = substrings[0],
                Name = substrings[1],
                Street = substrings[2],
                HouseNumber = substrings[3],
                PostalCode = substrings[4],
                City = substrings[5],
                PhoneAreaCode = substrings[6],
                PhoneNumber = substrings[7],
                Email = substrings[8]
            };
            PersonList.Add(person);
        }

    }
相关文章: