开发者

Assign dynamically generated image to ToggleButton.Content

开发者 https://www.devze.com 2023-02-02 22:33 出处:网络
I have to put dynamicall开发者_StackOverflow社区y generated image var img = new Bitmap(..); // draw something on img canvas ...

I have to put dynamicall开发者_StackOverflow社区y generated image

var img = new Bitmap(..);
// draw something on img canvas ...

To the ToggleButton background. When I assign generated image to ToggleButton.Content property I see "System.Drawing.Bitmap" string, not the image itself. It looks like ToString() method is used for Content property. How can I show generated image instead?


If WPF does not have an appropriate converter it just calls the ToString() method, the Bitmap format is unsuitable, what you normally want to use is an Image with a source that is a BitmapImage, there are several ways to do conversions between the different formats.
Here is one method that does a conversion from Bitmap to BitmapImage:

public static BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
    MemoryStream ms = new MemoryStream();
    bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    BitmapImage bImg = new System.Windows.Media.Imaging.BitmapImage();

    bImg.BeginInit();
    bImg.StreamSource = new MemoryStream(ms.ToArray());
    bImg.CreateOptions = BitmapCreateOptions.None;
    bImg.CacheOption = BitmapCacheOption.Default;
    bImg.EndInit();

    ms.Close();

    return bImg;
}

Note that ImageFormat.Png is slower than uncompressed formats but it retains the transparency if there is any.
Now you should be able to use this as the Source of an Image control and this Image control as the content of the button.


"Content" property is concerned with what you write on the surface of the ToggleButton. You need to initialize the "Background" property of the UI element. Here is one example:

        PixelFormat pf = PixelFormats.Bgr32;
        int width = 200;
        int height = 200;
        int rawStride = (width * pf.BitsPerPixel + 7) / 8;
        byte[] rawImage = new byte[rawStride * height];

        // Initialize the image with data.
        Random value = new Random();
        value.NextBytes(rawImage);

        // Create a BitmapSource.
        BitmapSource bitmap = BitmapSource.Create(width, height, 96, 96, pf, null, rawImage, rawStride);

        ImageBrush imgBrush = new ImageBrush(bitmap);
        myToggleButton.Background = imgBrush;

I created the image using the following article http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource(VS.85).aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消