我有一个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>
每当应将新图片添加到列表中时,都会从“头像”类中实例化一个对象并将其添加到列表中。
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)时,似乎对头像对象的更改不会传播到实际图像。为什么会这样?
答案 0 :(得分: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");
}
}
}
答案 1 :(得分: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));
}
}
}
它将始终更新您对头像属性所做的任何更改..如果您想要添加和del上的头像更改...要么使其成为一个observablecollection