文章的内容是来自微软中文技术论坛的一个帖子,当时是想将一段将图片灰度处理的代码转换为XAML的一个样式,在这里要谢谢
Xiao Yan Qiang、Sheldon _Xiao、shixin 的热情回答,现在将他们的回答贴出来供大家学习参考.内容如下:
提问: 这个功能如何写成一个样式,将一个窗体内所有的Image控件的图片格式都转换为Gray8
BitmapImage bitmapImage = new BitmapImage(newUri("D:\\Face.jpg"));
FormatConvertedBitmap newFormatedBitmapSource =new FormatConvertedBitmap();
newFormatedBitmapSource.BeginInit();
newFormatedBitmapSource.Source = bitmapImage;
newFormatedBitmapSource.DestinationFormat = PixelFormats.Gray8;
newFormatedBitmapSource.EndInit();
img.Source = newFormatedBitmapSource;
this.Content = img;
Xiao Yan Qiang的回答:
public class ImageAttached
{
// Gray8附加属性,Gary8图片样式的"开关" public static readonly DependencyProperty Gray8Property =
DependencyProperty.RegisterAttached("Gray8", typeof(bool), typeof(ImageAttached),
new FrameworkPropertyMetadata((bool)false,
new PropertyChangedCallback(OnGray8Changed)));
public static bool GetGray8(DependencyObject d)
{
return (bool)d.GetValue(Gray8Property);
}
public static void SetGray8(DependencyObject d, bool value)
{
d.SetValue(Gray8Property, value);
}
private static void OnGray8Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Image currentImage = d as Image;
if (currentImage == null)
{
return;
}
bool isGray8 = (bool)d.GetValue(Gray8Property);
if (isGray8)
{
// 附加BitmapSourceBackup属性,备份当前BitmapSource,以备恢复用
BitmapSource backupBitmapSource = (currentImage.Source as BitmapSource).CloneCurrentValue();
d.SetValue(BitmapSourceBackupPro