绑定到从Active Directory检索到的BitmapImage不起作用

时间:2014-04-29 15:38:07

标签: c# wpf active-directory bitmapimage

我有一段代码从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;
                }
            }

问题是视图中的图像没有任何更新。我调试了正在创建的图像,它看起来 ok ,但是调试工具不支持预览该类型,因此很难验证。我尝试绑定到64位编码的图像字符串,但没有运气。任何帮助或指导将不胜感激。

1 个答案:

答案 0 :(得分:1)

如果要在初始化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中的备注部分:

  

如果要关闭a,请将CacheOption设置为BitmapCacheOption.OnLoad   用于创建BitmapImage的流。 ...