I have a piece of code that retrieves a user's image from Active Directory and then updates a bound BitmapImage property with it.

The XAML looks like:

            <Image Width="30"
                   Height="30"
                   Margin="10"
                   DockPanel.Dock="Left"
                   Source="{Binding UserImage}"
                   VerticalAlignment="Top" />

The property is defined as:

        public BitmapImage UserImage
        {
            get
            {
                return _userImage;
            }
            set
            {
                if (_userImage != value)
                {
                    _userImage = value;
                    PropertyChanged(this, new PropertyChangedEventArgs("UserImage"));
                }
            }
        }

Finally, the code that updates the property is:

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

The problem is the image in the view is not being updated with anything. I have debugged the image being created and it looks ok, however the debugging tool doesn't support previewing that type so it's hard to verify. I have tried binding to an 64 bit encoded image string instead but had no luck. Any help or guidance would be appreciated.

有帮助吗?

解决方案

You have to set BitmapCacheOptions.OnLoad when you want to close the stream directly after initializing the BitmapImage:

var userImage = new BitmapImage();

using (var stream = new MemoryStream(...))
{
    userImage.BeginInit();
    userImage.CacheOption = BitmapCacheOption.OnLoad;
    userImage.StreamSource = stream;
    userImage.EndInit();
}

UserImage = userImage;

See the Remarks section in BitmapImage.CacheOption:

Set the CacheOption to BitmapCacheOption.OnLoad if you wish to close a stream used to create the BitmapImage. ...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top