简体   繁体   中英

INotifyPropertyChanged in WPF

Try to understand WPF. This is my test classes:

    public partial class MainWindow : Window, INotifyPropertyChanged
{
    private ObservableCollection<string> _myList = new ObservableCollection<string>();

    public ObservableCollection<string> MyList
    {
        get { return _myList; }
        set
        {
            _myList = value;
            RaisePropertyChanged("_myList");
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        comboBox1.DataContext = _myList;
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        MyList = AnotherClass.SomeMethod();
    }

    public event PropertyChangedEventHandler PropertyChanged;

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

internal static class AnotherClass
{
    public static ObservableCollection<string> SomeMethod()
    {
        return new ObservableCollection<string> {"this","is","test"};
    }
}

And this is XAML

<Grid>
    <ComboBox Height="23" HorizontalAlignment="Left" Margin="65,51,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" ItemsSource="{Binding}" />
    <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="310,51,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>

How to make this code work? I want ComboBox data will be changed after I click on the button and MyList is updated. PropertyChangedEventHandler is always null.

The problem is that you are directly setting the original list onto the Window.DataContext , so nothing ever listens to the windows' PropertyChanged event.

To solve this, set the DataContext to the window itself:

this.DataContext = this;

and then change the Binding so refer to the property:

<ComboBox ItemsSource="{Binding MyList}" />

You will also need to change your property definition so that it raises the name of the property being changed, not the name of the member:

this.RaisePropertyChanged("MyList");

I think you have two problems:

1) binding should be: {Binding MyList}

2) on MyList setter you should use RaisePropertyChanged("MyList");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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