简体   繁体   中英

PropertyChanged in binding

I don't understand how the PropertyChanged event works in a binding context. Please consider this simple code:

public class ImageClass
{
    public Uri ImageUri { get; private set; }
    public int ImageHeight { get; set; }
    public int ImageWidth { get; set; }
    public ImageClass(string location)
    {
        //
    }        
}

public ObservableCollection<ImageClass> Images
{
    get { return (ObservableCollection<ImageClass>)GetValue(ImagesProperty); }
    set { SetValue(ImagesProperty, value); }
}

public static readonly DependencyProperty ImagesProperty = DependencyProperty.Register("Images", typeof(ObservableCollection<ImageClass>), typeof(ControlThumbnail), new PropertyMetadata(null));

at run-time I make changes to some element of the Images Collection:

Images[i].ImageWidth = 100;

It has no effect - as far as I understand because the PropertyChanged event is not defined and then not fired.

I'm a confused how to declare such an event and what I need to put inside the event handler function.

I tried to do this:

foreach (object item in Images)
{
    if (item is INotifyPropertyChanged)
    {
        INotifyPropertyChanged observable = (INotifyPropertyChanged)item;
        observable.PropertyChanged += new PropertyChangedEventHandler(ItemPropertyChanged);
    }
}

private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
}

Implement the INotifyPropertyChanged interface in your ImageClass like this:

public class ImageClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private int imageWidth;
    public int ImageWidth
    {
        get { return imageWidth; }
        set
        {
            imageWidth = value;
            PropertyChanged?.Invoke(this,
                new PropertyChangedEventArgs(nameof(ImageWidth)));
        }
    }

    ...
}

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