我有一段代码,可以从Active Directory中检索用户的映像,然后用它更新绑定的BitmapImage
属性。
XAML看起来像:
<Image Width="30"
Height="30"
Margin="10"
DockPanel.Dock="Left"
Source="{Binding UserImage}"
VerticalAlignment="Top" />
属性定义为:
public BitmapImage UserImage
{
get
{
return _userImage;
}
set
{
if (_userImage != value)
{
_userImage = value;
PropertyChanged(this, new PropertyChangedEventArgs("UserImage"));
}
}
}
最后,更新属性的代码是:
PrincipalContext principleContext = new PrincipalContext(ContextType.Domain, HAL_Globals.domain);
UserPrincipal user = UserPrincipal.FindByIdentity(principleContext, IdentityType.SamAccountName, HAL_Globals.domain + "\" + _usernameSearchText);
DirectoryEntry userEntry = (user.GetUnderlyingObject() as DirectoryEntry);
if (userEntry != null)
{
using (MemoryStream stream = new MemoryStream(userEntry.Properties["thumbnailPhoto"].Value as byte[]))
{
BitmapImage userImage = new BitmapImage();
userImage.BeginInit();
userImage.StreamSource = stream;
userImage.EndInit();
UserImage = userImage;
}
}
问题是视图中的图像没有更新任何内容。我已经调试了正在创建的映像,它看起来还可以,但是调试工具不支持预览该类型,所以很难验证。我尝试绑定到一个64位编码的图像字符串,但没有成功。如有任何帮助或指导,我们将不胜感激。
当您想在初始化BitmapImage:后直接关闭流时,必须设置BitmapCacheOptions.OnLoad
var userImage = new BitmapImage();
using (var stream = new MemoryStream(...))
{
userImage.BeginInit();
userImage.CacheOption = BitmapCacheOption.OnLoad;
userImage.StreamSource = stream;
userImage.EndInit();
}
UserImage = userImage;
请参阅BitmapImage.CacheOption:中的备注部分
将CacheOption设置为BitmapCacheOption。如果要关闭用于创建BitmapImage的流。。。