2011-01-07 94 views
1

我必须把动态生成的图像分配动态生成图像ToggleButton.Content

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

要切换按钮的背景。当我将生成的图像分配给ToggleButton.Content属性时,我会看到“System.Drawing.Bitmap”字符串,而不是图像本身。它看起来像ToString()方法用于Content属性。我如何显示生成的图像呢?

+0

我认为你需要覆盖默认控件模板用自己的一个做到这一点...或者,如果发现所创建的映像Togglebutton有一个DataTemplate字段,用它来代替:p – Machinarius 2011-01-07 23:13:42

回答

2

如果WPF不具有相应的转换器,它只是调用ToString()方法,位图格式是不合适的,通常要使用什么是Image与作为BitmapImage,有几种方法可以做到之间的转换源不同的格式。
下面是一个方法,确实从BitmapBitmapImage的转化:

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

注意ImageFormat.Png比未压缩格式速度较慢,但​​它保留了透明性,如果有的话。
现在,您应该可以将其用作图像控件的来源,并将此图像控件用作按钮的内容。

2

“内容”属性与您在ToggleButton表面上编写的内容有关。您需要初始化UI元素的“背景”属性。这里有一个例子:

 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; 

我使用下面的文章http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource(VS.85).aspx