0

我在 ItemsControl 块中有图片列表,如下所示

<ItemsControl Name="icAvatars">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                    <Grid>
                        <TextBlock Visibility="{Binding LdVis}" Text="Loading... "/>
                        <TextBlock Visibility="{Binding ErrVis}" Text="Error while loading the image."/>
                        <Image Source="{Binding ImgSrc}" Visibility="{Binding ImgVis}"/>
                    </Grid>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

每当应将新图片添加到列表中时,都会从 Avatar 类实例化一个对象并将其添加到列表中。

public class Avatar
{
    public BitmapImage ImgSrc { get; set; }
    public Visibility LdVis { get; set; }
    public Visibility ImgVis { get; set; }
    public Visibility ErrVis { get; set; }
}

Avatar avatar = new Avatar();
var bitmap = new BitmapImage(new Uri(uri));
bitmap.ImageOpened += (s, e) => avatar.ShowImage();
avatar.ImgSrc = bitmap;
icAvatars.Items.Add(avatar);

问题是,当图像被加载并且我尝试更改其可见性属性(通过使用 avatar.ImgVis)时,似乎化身对象的更改不会传播到实际图像。为什么会发生这种情况?

4

2 回答 2

3

您的Avatar类应该实现INotifyPropertyChanged接口,并且每次ImgVis更改属性时都PropertyChanged应该引发事件。同样的事情应该适用于可以在运行时更改的所有数据绑定属性。

public class Avatar : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

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

    private Visibility _imgVis;

    public Visibility ImgVis 
    { 
       get{ return _imgVis; }
       set
       { 
          if (value == _imgVis) return;
          _imgVis = value;
          NotifyPropertyChanged("ImgVis");
       }
    }
}
于 2013-07-15T13:01:25.320 回答
1
this is because you have not implement the inotifypropertychange on you avatar class so for doinng that just do like this..
public class Assignment  : INotifyPropertyChanged
{




    private Visibility _ImgVis ;
    public Visibility ImgVis 
    {
        get
        {
            return _ImgVis ;
        }
        set
        {
            _ImgVis  = value;
            FirePropertyChanged("ImgVis ");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void FirePropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

}

它会始终更新您对头像属性所做的任何更改..如果您想在添加和删除时对头像进行更改...要么使其成为可观察的集合

于 2013-07-15T13:01:55.687 回答