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

时间:2016-10-14 09:58:08

标签: c# wpf mvvm combobox observablecollection

我正在开发一个用于练习目的的小型MVVM WPF项目,我有两个窗口,每个窗口有一个视图,一个用于显示员工(MainWindow),另一个用于添加员工(AddPersonWindow)。

在我的MainWindow中,有一个ComboBox绑定到ObservableCollection,我可以从AddPersonWindow中的按钮打开MainWindow。但是,如果我通过单击“保存”按钮并执行AddPersonWindow函数从AddPerson()向ObservableCollection添加员工,则MainWindow中的ComboBox不会更新。如果我从AddPerson()执行完全相同的MainWindow函数,一切都很好,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();
    }

MainWindow.xaml中的ComboBox:

<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>

1 个答案:

答案 0 :(得分:0)

我没有设法共享一个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);
        }


    }