简体   繁体   English

更新ComboBox源不会更新ComboBox

[英]Updating ComboBox Source Doesn't Update ComboBox

I have a ComboBox whose ItemSource is bound to an ObservableCollection of type Person called PersonsList. 我有一个ComboBox,其ItemSource绑定到名为PersonsList的Person类型的ObservableCollection。 The DisplayMemberPath on this ComboBox is set to FullName (which just returns the First Name + Last Name) 此组合框上的DisplayMemberPath设置为FullName(它仅返回名字+姓氏)

Person has various things stored in it such as First Name, Last Name, Phone Number, Address, etc. 人员中存储着各种东西,例如名字,姓氏,电话号码,地址等。

Now when I update a person in PersonsList, I update the appropriate data fields and call OnPropertyChanged("PersonsList"). 现在,当我更新PersonsList中的一个人时,我将更新相应的数据字段并调用OnPropertyChanged(“ PersonsList”)。 Now my issue occurs when I go back to view that ComboBox. 现在,当我返回查看该ComboBox时,就会发生我的问题。 If I've updated the First or Last Name of a Person, it doesn't update here. 如果我已经更新了一个人的名字或姓氏,那么这里不会更新。 However, when I click on the person that should have been updated, it displays the newly updated first/last name correctly. 但是,当我单击应该更新的人时,它会正确显示新更新的名字。

Here are 2 pictures to see what I mean: https://imgur.com/a/fP6apoX 这是两张图片,以了解我的意思: https : //imgur.com/a/fP6apoX

Finally, here is my XAML code: 最后,这是我的XAML代码:

ComboBox ItemsSource="{Binding PersonsList, UpdateSourceTrigger=PropertyChanged}" 
DisplayMemberPath="FullName"/>

You need to modify your Person class as given below, since the property mapped with View belongs to the Person class, so the property changed event needs to be fired by the Person Class 您需要按如下所示修改您的Person类,因为用View映射的属性属于Person类,因此该属性更改事件需要由Person类触发

public class Person : INotifyPropertyChanged
{
    /// <summary>
    /// Property Changed Event Handler
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    // Create the OnPropertyChanged method to raise the event
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    private String _FirstName;
    public String FirstName {
        get {
            return _FirstName;
        }
        set {
            _FirstName = value;
            OnPropertyChanged(nameof(FirstName));
        }
    }

    private String _LastName;
    public String LastName
    {
        get
        {
            return _LastName;
        }
        set
        {
            _LastName = value;
            OnPropertyChanged(nameof(LastName));
        }
    }

    private String _FullName;
    public String FullName
    {
        get
        {
            return _FullName;
        }
        set
        {
            _FullName = value;
            OnPropertyChanged(nameof(FullName));
        }
    }


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM