最新的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構造函數創建一個音頻播放器對象來在網站上使用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的信號機制來構建一個簡單但功能強大的消息通知系統,并提供相應的代碼和實例。
首先,確保你已經安裝了 Django。你可以通過 pip 安裝它:
pip install django
創建一個 Django 項目,并在其中創建一個應用:
django-admin startproject notification_system
cd notification_system
python manage.py startapp notifications
在 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)
在 notifications/signals.py 文件中創建信號,該信號將在需要發送通知時觸發:
from django.dispatch import Signal
notification_sent = Signal(providing_args=["user", "message"])
在 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)
在你的應用程序中的適當位置,發送信號以觸發通知:
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='你有一個新消息')
在你的應用程序中,可以通過查詢通知模型來顯示用戶的通知:
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})
當用戶查看通知時,你可能需要將它們標記為已讀。你可以在視圖中執行此操作:
def mark_as_read(request, notification_id):
notification = Notification.objects.get(pk=notification_id)
notification.read = True
notification.save()
return redirect('notifications_view')
創建一個 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>
配置 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'),
]
運行 Django 服務器以查看效果:
python manage.py runserver
現在,你可以訪問 http://127.0.0.1:8000/notifications/ 查看通知頁面,并且點擊“標記為已讀”鏈接來標記通知。
為了提升通知頁面的用戶體驗,我們可以使用一些流行的前端框架來美化頁面并添加一些交互功能。這里以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>
我們可以使用 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})
為了讓用戶可以清晰地知道有多少未讀通知,我們可以添加一個通知計數的功能,將未讀通知的數量顯示在頁面上。
首先,在 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>
為了使通知計數實時更新,我們可以使用 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})
除了標記通知為已讀之外,有時用戶還可能希望能夠刪除一些通知,特別是一些不再需要的通知。因此,我們可以添加一個刪除通知的功能。
首先,在模板中為每個通知添加一個刪除按鈕:
<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>
在實際應用中,通知系統可能需要處理大量的通知,而生成和發送通知可能是一個耗時的操作。為了避免阻塞用戶請求,我們可以使用異步任務處理來處理通知的生成和發送。
首先,安裝 Celery 和 Redis 作為消息代理:
pip install celery redis
在 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'
在 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)
在你的應用程序中,當需要發送通知時,使用 Celery 的 delay() 方法觸發異步任務:
from notifications.tasks import send_notification
send_notification.delay(user_id, '你有一個新消息')
本文介紹了如何使用 Django 構建一個功能強大的消息通知系統,其中涵蓋了以下主要內容:
通過這些步驟,我們建立了一個功能完善的消息通知系統,用戶可以及時了解到與其相關的重要信息,并且可以自由地管理和處理通知,從而增強了應用的交互性、可用性和性能。
關注 #華為云開發者聯盟#點擊下方,第一時間了解華為云新鮮技術~
華為云博客_大數據博客_AI博客_云計算博客_開發者中心-華為云
*請認真填寫需求信息,我們會在24小時內與您取得聯系。