shtkuh
shtkuh

Reputation: 459

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.

Upvotes: 4

Views: 10438

Answers (2)

Teudimundo
Teudimundo

Reputation: 2670

I think you have two problems:

1) binding should be: {Binding MyList}

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

Upvotes: 2

Steve Greatrex
Steve Greatrex

Reputation: 15999

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");

Upvotes: 10

Related Questions