整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

界面控件DevExpress WinForms HTML & CSS模板-轻松创建警报通知

最新的DevExpress WinForm版本中,开发者可以使用WinForm产品线(通过DevExpress AlertControl和ToastNotificationManager)创建两种类型的通知/警报,最近技术团队还推荐使用DevExpress ToastNotificationManager来显示原生 Windows 10+ 通知。

DevExpress Universal Subscription官方最新版免费下载试用,历史版本下载,在线文档和帮助文件下载-慧都网

尽管自定义选项有些有限(toast 仅提供九个布局模板),但ToastNotificationManager 代表了比传统的基于面板的AlertControl更好、更现代的替代方案。

在最新版中为AlertControl发布的HTML & CSS 模板,允许开发人员创建时尚的警告通知,同时可利用AlertControl 本身的简单性。下图说明了技术团队提供的一些示例模板(查找您喜欢的模板并将其复制到项目中):

大多数通知只是一个带有几个文本块、图像和按钮的矩形,设计这样简单的对象对每个人来说都应该相对容易——无论您有 HTML 和 CSS 经验,还是开始在WinForms 应用程序中利用其潜力。 例如以下模板创建一个带有图标、标题、描述和“确定”按钮的通知。

<div class="container">
<div class="popup">
<img src="${SvgImage}" class="image" />
<div class="caption">Notification Title</div>
<div class="text">This notification uses a web-inspired template.</div>
<div id="okButton" class="ok-button">OK</div>
</div>
</div>

请注意,在此示例标记中,通知标题和说明是静态字符串。 如果您要为用户显示一条消息,此解决方案就可以正常工作。

当然我们的数据绑定功能提供了更大的灵活性——您可以创建一个模板并将不同的数据对象传递给它。 因此,您可以为多个通知消息重用一个模板。

如果您更喜欢此选项,请使用 ${Data_property_name} 占位符,如下所示:

<div class="text">${Caption}</div>
<div class="text">${Text}</div>

“Caption”和“Text”是标准占位符,可以通过 AlertControl.Show 重载直接替换:

alertControl1.Show(this, "Sample caption", "Sample notification text");

您可以添加模板设计所需的任意数量的占位符,但请记住处理 AlertControl.BeforeFormShow 事件并将数据对象传递给 e.HtmlPopup.DataContext 属性。 例如,下面的代码使用 div 元素来显示由五个占位符组合而成的字符串:两个用于字符串值(FullName、Ticker),两个用于数字(Percentage、Price),一个用于自定义 Direction 枚举值。

<div class="message-text">
${FullName} ({Ticker}) {Direction} {Percentage}%. The current price is ${Price}.
</div>

通知图像也在运行时检索,img 标签使用占位符替代静态 src 属性值。

<img src="${StockImage}" class="message-image" />

此示例应用程序使用 StockInfo 类对象作为数据项。

public class StockInfo {
public StockInfo(string ticker, string fullName, Direction direction,
double percentage, double price, SvgImage img) {
Ticker = ticker;
FullName = fullName;
Direction = direction;
Percentage = percentage;
Price = price;
StockImage = img;
}

public string Ticker { get; set; }
public string FullName { get; set; }
public Direction Direction { get; set; }
public double Percentage { get; set; }
public double Price { get; set; }
public SvgImage StockImage { get; set; }
}

public enum Direction {
[Description("rises")]
Up,
[Description("falls")]
Down
}

当数据项的 "Price" 值在短时间内发生显着变化时会触发通知,相应的项目分配给 AlertControl.BeforeFormShow 事件处理程序中的 e.HtmlPopup.DataContext 属性。

void AlertControl1_BeforeFormShow(object sender, AlertFormEventArgs e) {
// TODO: Retrieve a data item
e.HtmlPopup.DataContext = myStockInfoInstance;
}

因此,通知会从指定为 DataContext 的数据项中检索其 ${Field_Name} 占位符的数据。 请注意,边条的颜色会根据 "Direction" 枚举值而变化。

DevExpress WinForm

DevExpress WinForm拥有180+组件和UI库,能为Windows Forms平台创建具有影响力的业务解决方案。DevExpress WinForms能完美构建流畅、美观且易于使用的应用程序,无论是Office风格的界面,还是分析处理大批量的业务数据,它都能轻松胜任!

载说明:原创不易,未经授权,谢绝任何形式的转载

有时候,我们需要通过JavaScript在网站上播放通知声音。本文将介绍如何实现这一功能。

使用Audio构造函数在网站上播放通知声音

我们可以通过使用Audio构造函数创建一个音频播放器对象来在网站上使用JavaScript播放通知声音。

例如,如果我们有以下按钮:

<button>Play</button>

然后,我们可以通过编写以下代码来使用Audio构造函数,在点击按钮时播放音频剪辑:

const playAudio = (url) => {

const audio = new Audio(url);

audio.play();

}

const button = document.querySelector('#play-button');

button.addEventListener('click', () => {

const audioUrl = 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3';

playAudio(audioUrl);

console.log(`Now playing audio from ${audioUrl}`);

});

这段代码定义了一个名为`playAudio`的函数,它接受一个URL参数,用于指定要播放的音频文件的路径。当调用`playAudio`函数时,它会创建一个新的`Audio`对象并播放指定的音频文件。

接下来,使用`querySelector`方法获取网页中的一个ID为`play-button`的元素,并将其存储在`button`变量中。然后,使用`addEventListener`方法为`button`元素添加一个`click`事件监听器。当按钮被点击时,触发回调函数。在回调函数中,我们定义了一个名为`audioUrl`的常量,它存储了所需的音频文件的URL。然后,我们调用`playAudio`函数并将`audioUrl`作为参数传递给它,以便播放指定的音频文件。最后,我们将一条消息记录到控制台,指示正在播放哪个音频文件。

结束

我们可以使用JavaScript通过使用Audio构造函数创建一个音频播放器对象来在网站上播放通知声音。

由于文章内容篇幅有限,今天的内容就分享到这里,文章结尾,我想提醒您,文章的创作不易,如果您喜欢我的分享,请别忘了点赞和转发,让更多有需要的人看到。同时,如果您想获取更多前端技术的知识,欢迎关注我,您的支持将是我分享最大的动力。我会持续输出更多内容,敬请期待。

文分享自华为云社区《构建实时消息通知系统:Django实战指南-云社区-华为云》,作者:柠檬味拥抱。

在Web应用程序中,实现消息通知系统是至关重要的,它可以帮助用户及时了解到与其相关的事件或动态。Django提供了信号机制,可以用于实现这样的通知系统。本文将介绍如何使用Django的信号机制来构建一个简单但功能强大的消息通知系统,并提供相应的代码和实例。

1. 安装 Django

首先,确保你已经安装了 Django。你可以通过 pip 安装它:

pip install django

2. 创建 Django 项目和应用

创建一个 Django 项目,并在其中创建一个应用:

django-admin startproject notification_system
cd notification_system
python manage.py startapp notifications

3. 定义模型

notifications/models.py 文件中定义一个模型来存储通知信息:

from django.db import models
from django.contrib.auth.models import User

class Notification(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    message = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    read = models.BooleanField(default=False)

4. 创建信号

notifications/signals.py 文件中创建信号,该信号将在需要发送通知时触发:

from django.dispatch import Signal

notification_sent = Signal(providing_args=["user", "message"])

5. 编写信号处理器

notifications/handlers.py 文件中编写信号处理器,处理信号并创建相应的通知:

from django.dispatch import receiver
from .signals import notification_sent
from .models import Notification

@receiver(notification_sent)
def create_notification(sender, **kwargs):
    user = kwargs['user']
    message = kwargs['message']
    Notification.objects.create(user=user, message=message)

6. 发送通知

在你的应用程序中的适当位置,发送信号以触发通知:

from django.contrib.auth.models import User
from notifications.signals import notification_sent

# 例如,发送通知给特定用户
user = User.objects.get(username='username')
notification_sent.send(sender=None, user=user, message='你有一个新消息')

7. 显示通知

在你的应用程序中,可以通过查询通知模型来显示用户的通知:

from notifications.models import Notification

# 例如,在视图中查询并显示通知
def notifications_view(request):
    user_notifications = Notification.objects.filter(user=request.user)
    return render(request, 'notifications.html', {'notifications': user_notifications})

8. 标记通知为已读

当用户查看通知时,你可能需要将它们标记为已读。你可以在视图中执行此操作:

def mark_as_read(request, notification_id):
    notification = Notification.objects.get(pk=notification_id)
    notification.read = True
    notification.save()
    return redirect('notifications_view')

9. 定义通知模板

创建一个 HTML 模板来呈现通知信息。在 templates/notifications.html 文件中定义:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notifications</title>
</head>
<body>
    <h1>Notifications</h1>
    <ul>
        {% for notification in notifications %}
        <li{% if notification.read %} style="color: grey;"{% endif %}>
            {{ notification.message }}
            {% if not notification.read %}
            <a href="{% url 'mark_as_read' notification.id %}">Mark as Read</a>
            {% endif %}
        </li>
        {% endfor %}
    </ul>
</body>
</html>

10. 配置 URL

配置 URL 来处理通知相关的请求。在 notification_system/urls.py 文件中:

from django.urls import path
from notifications.views import notifications_view, mark_as_read

urlpatterns = [
    path('notifications/', notifications_view, name='notifications_view'),
    path('notifications/mark_as_read/<int:notification_id>/', mark_as_read, name='mark_as_read'),
]

11. 运行服务器

运行 Django 服务器以查看效果:

python manage.py runserver

现在,你可以访问 http://127.0.0.1:8000/notifications/ 查看通知页面,并且点击“标记为已读”链接来标记通知。

12. 集成前端框架

为了提升通知页面的用户体验,我们可以使用一些流行的前端框架来美化页面并添加一些交互功能。这里以Bootstrap为例。

首先,安装Bootstrap:

pip install django-bootstrap4

settings.py 中配置:

INSTALLED_APPS = [
    ...
    'bootstrap4',
    ...
]

修改通知模板 notifications.html,引入Bootstrap的样式和JavaScript文件,并使用Bootstrap的组件来美化页面:

{% load bootstrap4 %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notifications</title>
    {% bootstrap_css %}
</head>
<body>
    <div class="container">
        <h1 class="mt-5">Notifications</h1>
        <ul class="list-group mt-3">
            {% for notification in notifications %}
            <li class="list-group-item{% if notification.read %} list-group-item-light{% endif %}">
                {{ notification.message }}
                {% if not notification.read %}
                <a href="{% url 'mark_as_read' notification.id %}" class="btn btn-sm btn-primary ml-2">Mark as Read</a>
                {% endif %}
            </li>
            {% endfor %}
        </ul>
    </div>
    {% bootstrap_javascript %}
</body>
</html>

13. 使用 Ajax 实现标记为已读功能

我们可以使用 Ajax 技术来实现标记通知为已读的功能,这样可以避免刷新整个页面。修改模板文件和视图函数如下:

在模板中,使用 jQuery 来发送 Ajax 请求:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        $('.mark-as-read').click(function(e) {
            e.preventDefault();
            var url = $(this).attr('href');
            $.ajax({
                type: 'GET',
                url: url,
                success: function(data) {
                    if (data.success) {
                        window.location.reload();
                    }
                }
            });
        });
    });
</script>

修改视图函数 mark_as_read

from django.http import JsonResponse

def mark_as_read(request, notification_id):
    notification = Notification.objects.get(pk=notification_id)
    notification.read = True
    notification.save()
    return JsonResponse({'success': True})

14. 添加通知计数功能

为了让用户可以清晰地知道有多少未读通知,我们可以添加一个通知计数的功能,将未读通知的数量显示在页面上。

首先,在 notifications/views.py 中修改 notifications_view 视图函数:

def notifications_view(request):
    user_notifications = Notification.objects.filter(user=request.user)
    unread_count = user_notifications.filter(read=False).count()
    return render(request, 'notifications.html', {'notifications': user_notifications, 'unread_count': unread_count})

然后,在通知模板中显示未读通知的数量:

<div class="container">
    <h1 class="mt-5">Notifications</h1>
    <div class="alert alert-info mt-3" role="alert">
        You have {{ unread_count }} unread notification(s).
    </div>
    <ul class="list-group mt-3">
        {% for notification in notifications %}
        <li class="list-group-item{% if notification.read %} list-group-item-light{% endif %}">
            {{ notification.message }}
            {% if not notification.read %}
            <a href="{% url 'mark_as_read' notification.id %}" class="btn btn-sm btn-primary ml-2 mark-as-read">Mark as Read</a>
            {% endif %}
        </li>
        {% endfor %}
    </ul>
</div>

15. 实时更新通知计数

为了使通知计数实时更新,我们可以使用 Ajax 技术定期请求服务器以获取最新的未读通知数量。

在通知模板中添加 JavaScript 代码:

<script>
    function updateUnreadCount() {
        $.ajax({
            type: 'GET',
            url: '{% url "unread_count" %}',
            success: function(data) {
                $('#unread-count').text(data.unread_count);
            }
        });
    }
    $(document).ready(function() {
        setInterval(updateUnreadCount, 5000); // 每5秒更新一次
    });
</script>

notifications/urls.py 中添加一个新的 URL 路由来处理未读通知数量的请求:

from django.urls import path
from .views import notifications_view, mark_as_read, unread_count

urlpatterns = [
    path('notifications/', notifications_view, name='notifications_view'),
    path('notifications/mark_as_read/<int:notification_id>/', mark_as_read, name='mark_as_read'),
    path('notifications/unread_count/', unread_count, name='unread_count'),
]

最后,在 notifications/views.py 中定义 unread_count 视图函数:

from django.http import JsonResponse

def unread_count(request):
    user_notifications = Notification.objects.filter(user=request.user, read=False)
    unread_count = user_notifications.count()
    return JsonResponse({'unread_count': unread_count})

16. 添加通知删除功能

除了标记通知为已读之外,有时用户还可能希望能够删除一些通知,特别是一些不再需要的通知。因此,我们可以添加一个删除通知的功能。

首先,在模板中为每个通知添加一个删除按钮:

<ul class="list-group mt-3">
    {% for notification in notifications %}
    <li class="list-group-item{% if notification.read %} list-group-item-light{% endif %}">
        {{ notification.message }}
        <div class="btn-group float-right" role="group" aria-label="Actions">
            {% if not notification.read %}
            <a href="{% url 'mark_as_read' notification.id %}" class="btn btn-sm btn-primary mark-as-read">Mark as Read</a>
            {% endif %}
            <a href="{% url 'delete_notification' notification.id %}" class="btn btn-sm btn-danger delete-notification">Delete</a>
        </div>
    </li>
    {% endfor %}
</ul>

然后,在 notifications/urls.py 中添加一个新的 URL 路由来处理删除通知的请求:

urlpatterns = [
    ...
    path('notifications/delete/<int:notification_id>/', delete_notification, name='delete_notification'),
]

接着,在 notifications/views.py 中定义 delete_notification 视图函数:

def delete_notification(request, notification_id):
    notification = Notification.objects.get(pk=notification_id)
    notification.delete()
    return redirect('notifications_view')

最后,为了使用户可以通过 Ajax 删除通知,我们可以修改模板中的 JavaScript 代码:

<script>
    $(document).ready(function() {
        $('.delete-notification').click(function(e) {
            e.preventDefault();
            var url = $(this).attr('href');
            $.ajax({
                type: 'GET',
                url: url,
                success: function(data) {
                    if (data.success) {
                        window.location.reload();
                    }
                }
            });
        });
    });
</script>

17. 添加异步任务处理

在实际应用中,通知系统可能需要处理大量的通知,而生成和发送通知可能是一个耗时的操作。为了避免阻塞用户请求,我们可以使用异步任务处理来处理通知的生成和发送。

17.1 安装 Celery

首先,安装 Celery 和 Redis 作为消息代理:

pip install celery redis

17.2 配置 Celery

在 Django 项目的根目录下创建一个名为 celery.py 的文件,并添加以下内容:

import os
from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'notification_system.settings')

app = Celery('notification_system')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

settings.py 中添加 Celery 配置:

CELERY_BROKER_URL = 'redis://localhost:6379/0'

17.3 创建异步任务

notifications/tasks.py 中定义异步任务来处理通知的生成和发送:

from celery import shared_task
from .models import Notification

@shared_task
def send_notification(user_id, message):
    user = User.objects.get(pk=user_id)
    Notification.objects.create(user=user, message=message)

17.4 触发异步任务

在你的应用程序中,当需要发送通知时,使用 Celery 的 delay() 方法触发异步任务:

from notifications.tasks import send_notification

send_notification.delay(user_id, '你有一个新消息')

总结:

本文介绍了如何使用 Django 构建一个功能强大的消息通知系统,其中涵盖了以下主要内容:

  1. 通过定义模型、创建信号、编写信号处理器,实现了通知系统的基本框架。
  2. 集成了前端框架 Bootstrap,并使用 Ajax 技术实现了标记通知为已读的功能,以及实时更新未读通知数量的功能,提升了用户体验。
  3. 添加了通知删除功能,使用户可以更灵活地管理通知。
  4. 引入了异步任务处理技术 Celery,将通知的生成和发送操作转换为异步任务,提高了系统的性能和响应速度。

通过这些步骤,我们建立了一个功能完善的消息通知系统,用户可以及时了解到与其相关的重要信息,并且可以自由地管理和处理通知,从而增强了应用的交互性、可用性和性能。

关注 #华为云开发者联盟#点击下方,第一时间了解华为云新鲜技术~

华为云博客_大数据博客_AI博客_云计算博客_开发者中心-华为云