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

     在《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

源代码下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值