2017-03-09 48 views
1

我不明白PropertyChanged事件如何在绑定上下文中工作。 请考虑这个简单的代码:PropertyChanged in binding

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

在运行时我更改了Images收集的一些元素:

Images[i].ImageWidth = 100; 

它没有效果 - 据我理解,因为PropertyChanged事件没有定义,然后不被解雇。

我很困惑如何声明这样的事件,我需要把事件处理函数放在里面。

我试着这样做:

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) 
{ 
} 
+0

它你有设置对象的值(后后触发一个事件设置者Setvalue),并在你的视图中设置{Binding YourObject,UpdateSourceTrigger = PropertyChanged} ...这样视图就会知道属性改变了它的值,并会要求获取者获取新值:) –

+1

@BernardWalters请注意t帽子'UpdateSourceTrigger = PropertyChanged'与实现INotifyPropertyChanged并触发PropertyChanged事件的绑定源无关。实际上,UpdateSourceTrigger控制着一个TwoWay或OneWayToSource绑定如何在目标对象发生变化时触发源对象的更新,这在OneWay绑定中是不会发生的。 – Clemens

回答

3

ImageClass落实INotifyPropertyChanged界面是这样的:

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

    ... 
} 
+0

你能解释一下Invoke语句的语法吗?我以前没见过这种味道。 –

+1

这就是[null-conditional operator](https://msdn.microsoft.com/en-us/library/dn986595.aspx)。它可以节省您对事件的空检查。 – Clemens

+0

明白了,谢谢!我能够扩展到所有其他属性。只是澄清:根据伯纳德的评论,当我需要在视图中设置“{Binding YourObject,UpdateSourceTrigger = PropertyChanged}”时? – Mark