wpf 如何实现窗口恢复按钮变灰
这是一个比较常见的需求,研究了一下,找到设置图片灰度显示和恢复彩色显示的方法,接下来,将用一个case来描述这个实现过程:窗口包含一张彩色图片和两个按钮,点击一个按钮,图片显示灰白两色,点击另外一个按钮,图片显示彩色。
窗口代码:
[csharp] view plaincopyprint?
<Window x:Class="TestForWpf.Grayscale"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Grayscale" Height="376" Width="685">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="136*" />
<RowDefinition Height="201*" />
</Grid.RowDefinitions>
<Image Source="/TestForWpf;component/Images/icon.png" Name="img0" Height="120" Width="120" Margin="257,48,286,169" Grid.RowSpan="2"></Image>
<Button Name="setGrayscale" Content="Set Grayscale" Width="120" Height="30" Margin="99,101,0,70" Click="setGrayscale_Click" HorizontalAlignment="Left" Grid.Row="1"></Button>
<Button Name="setDefault" Content="Set Default" Height="30" Margin="414,101,129,70" Width="120" Click="setDefault_Click" Grid.Row="1" />
</Grid>
</Window>
后台代码:
[csharp] view plaincopyprint?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace TestForWpf
{
/// <summary>
/// Interaction logic for Grayscale.xaml
/// </summary>
public partial class Grayscale : Window
{
public Grayscale()
{
InitializeComponent();
}
private void setGrayscale_Click(object sender, RoutedEventArgs e)
{
SetGrayscale(img0);
}
private void setDefault_Click(object sender, RoutedEventArgs e)
{
SetDefalut(img0);
}
private void SetGrayscale(System.Windows.Controls.Image img)
{
// Set image grayscale
img.IsEnabled = false;
FormatConvertedBitmap bitmap = new FormatConvertedBitmap();
bitmap.BeginInit();
bitmap.Source = (BitmapSource)img.Source;
bitmap.DestinationFormat = PixelFormats.Gray32Float;
bitmap.EndInit();
img.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() => { img.Source = bitmap; }));
}
private void SetDefalut(System.Windows.Controls.Image img)
{
img.IsEnabled = true;
BitmapImage tempImg = new BitmapImage();
tempImg.BeginInit();
tempImg.UriSource = new Uri("pack://application:,,,/TestForWpf;component/Images/icon.png");
tempImg.EndInit();
img.Source = tempImg;
}
}
}
SetGrayscale是设置图片灰度显示,通过FormatConvertedBitmap类来进行转化。
SetDefalut是恢复图片彩色显示,这里图片的路径写了一些hardcode,当然,这不是重点,重点是它确实恢复了颜色。
效果图: