Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 385
shtkuh Avatar asked Dec 16 '22 07:12

shtkuh


1 Answers

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");
like image 95
Steve Greatrex Avatar answered Dec 18 '22 23:12

Steve Greatrex