WPF 4 动态覆盖图标(Dynamic Overlay Icon)

来源:互联网 发布:linux设备驱动开发详解 编辑:程序博客网 时间:2024/05/20 07:33
在《WPF 4 开发Windows 7 任务栏》一文中我们学习了任务栏的相关开发内容,同时也对覆盖图标(Overlay Icon)功能进行了一些介绍,其中覆盖图标是以静态方式呈现的。本篇将进一步制作覆盖图标的动态实例。

新建应用程序

在项目中添加应用程序图标资源(App.ico),通过Window 属性为应用程序设置图标。

Icon

Property

ChooseIcon

在XAML 页面添加一个“Show Overlay Icon” <Button>控件用于触发后面显示动态覆盖图标的点击事件。

XAML

<Grid>    <Button x:Name="showBtn" Content="Show Overlay Icon"             Height="30" Width="120" Click="showBtn_Click"/></Grid>

设置图标模板

     为了使用方便我们通过Window Resource 设置一个图标数据模板(DataTemplate)。由一个绿色圆圈(Ellipse)和一个文本框(TextBlock)组成,文本框用于动态显示倒计时数字。

<Window.Resources>    <DataTemplate x:Key="DynamicIcon">        <Grid Width="20" Height="20">            <Ellipse Fill="Green" Stroke="White" StrokeThickness="2"/>            <TextBlock Text="{Binding}" TextAlignment="Center" Foreground="White"                        FontWeight="Bold" Height="16" VerticalAlignment="Center"                         FontSize="12"/>        </Grid>    </DataTemplate></Window.Resources>

添加任务栏组件

在XAML 中添加TaskbarItemInfo 组件,支持覆盖图标显示。

<Window x:Class="Win7TaskbarDemo.MainWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        Title="MainWindow" Height="211" Width="363"         Icon="/Win7TaskbarDemo;component/Resources/App.ico">    <Window.Resources>        … …    </Window.Resources>    <Window.TaskbarItemInfo>        <TaskbarItemInfo />    </Window.TaskbarItemInfo>    <Grid>        <Button x:Name="showBtn" Content="Show Overlay Icon"                 Height="30" Width="120" Click="showBtn_Click"/>    </Grid></Window>

添加点击事件

最后为按键添加点击事件,如下代码:

private void showBtn_Click(object sender, RoutedEventArgs e){    int iconWidth = 20;    int iconHeight = 20;    for (int i = 10; i > 0; i--)    {        RenderTargetBitmap bmp = new RenderTargetBitmap(iconWidth, iconHeight, 96, 96, PixelFormats.Default);        ContentControl ctl = new ContentControl();        ctl.ContentTemplate = ((DataTemplate)Resources["DynamicIcon"]);        ctl.Content = i.ToString();        ctl.Arrange(new Rect(0, 0, iconWidth, iconHeight));        bmp.Render(ctl);        TaskbarItemInfo.Overlay = (ImageSource)bmp;        Thread.Sleep(1000);    }}

     上面代码中,主要思路是通过循环将i值显示在覆盖图标中,以达到倒计时的效果。RenderTargetBitmap 允许我们通过XAML创建视图并将其渲染成Bitmap,当然这个Bitmap 图片就是要为TaskbarItemInfo 设置的Overlay 属性。

     接下来通过ContentControl 为DynamicIcon 模板设置覆盖图标资源,并将i值Binding 到TextBlock 控件。最后通过Render 方法将ContentControl 渲染为Bitmap,并赋给TaskbarItemInfo 的Overlay 属性。

运行程序点击“Show Overlay Icon”按键后,覆盖图标便以倒计时10秒方式动态显示。

10    8    1