[ Windows Phone 8.1 ] Status Bar And Messages Queue Info Wrapper

Использование StatusBar в WP8.1 и обёртка для него

Одна из самых часто используемых штук в Windows Phone — это StatusBar, и он, как и многое другое, был стандартизирован и теперь работа с ним выглядит совсем иначе, но зато удобнее.

// Получаем текущий statusBar / Get current StatusBar
var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
// Устанавливаем фон и всякие плюшки / Set Background
statusBar.BackgroundColor = (App.Current.Resources["PhoneAccentBrush"] as SolidColorBrush).Color;
statusBar.BackgroundOpacity = 1;

// Устанавливаем текст Set the text on the ProgressIndicator
statusBar.ProgressIndicator.Text = "class.expert";

// Показываем индикатор / show
statusBar.ProgressIndicator.ShowAsync();

// Устанавливаем: 0 - нет прогресса, null - точечки, 0..1 - отображаем прогресс, к примеру загрузки / Set it to 0 if you don't wish to show the progress bar.

statusBar.ProgressIndicator.ProgressValue = 0;

 

А чтобы было ещё удобнее, я так, ради смеха, написал к нему обёртку. Мне пока не надо, но просто хотелось поиграться, на будущее.

Можно использовать как угодно, но:

1. В реальных условиях я ещё не тестировал

2. Копирайты сохраняем, даже при модификации

3. Заглядывайте за обновлением, скорее всего рано или поздно оно мне понадобиться и будут реализованы новые ништяки.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;

// You can use this code as you want
// You should respect copyrights and save it in any cases
// CopyRight http://class.expert/
namespace App3
{
    /// <summary>Wrapper for StatusBar in Windows Phone 8.1</summary>
    public static class Info
    {
        private static StatusBar _statusBar { get { return StatusBar.GetForCurrentView(); } }
        private static DispatcherTimer _msgTimer;
        private static Queue<string> _messages;
        public static int Count { get { return _messages == null ? 0 : _messages.Count; } }

        /// <summary>Initialize and Show Status Bar</summary>
        /// <param name=" messageInterval">Interval between messages in queue
        public static void Init(TimeSpan messageInterval)
        {
            _messages = new Queue<string>();
            _msgTimer = new DispatcherTimer();
            _msgTimer.Interval = messageInterval;
            _msgTimer.Tick += _msgTimer_Tick;
            Show();
        }

        /// <summary>Initialize and Show Status Bar with 5 sec interval</summary>
        public static void Init()
        {
            Init(TimeSpan.FromSeconds(5));
        }

        /// <summary>Show CURRENT ProgressIndicator in StatusBar</summary>
        public async static void Show()
        {
            StopProgress();
            await _statusBar.ProgressIndicator.ShowAsync();
        }

        public static void StartIndeterminate()
        {
            _statusBar.ProgressIndicator.ProgressValue = null;
        }

        public static void SetProgress(double val)
        {
            _statusBar.ProgressIndicator.ProgressValue = val;
        }

        /// <summary>Stop any progress</summary>
        public static void StopProgress()
        {
            _statusBar.ProgressIndicator.ProgressValue = 0;
        }

        /// <summary>Add message to messages queue</summary>
        public static void Add(string msg)
        {
            _messages.Enqueue(msg);
            Resume();
        }

        /// <summary>end current info and show other just now</summary>
        public static void QuickInform(string msg)
        {
            _msgTimer.Stop();
            SetText(msg);
            Resume();
        }

        /// <summary>clear messages queue and current info</summary>
        public static void Clear()
        {
            _msgTimer.Stop();
            _messages.Clear();
            SetText(string.Empty);
        }

        /// <summary>set permament text and stop messages queue</summary>
        public static void SetTextAndStop(string text)
        {
            Stop();
            SetText(text);
        }

        /// <summary>stop messages queue</summary>
        public static void Stop()
        {
            _msgTimer.Stop();
        }

        /// <summary>resume messages queue</summary>
        public static void Resume()
        {
            if (!_msgTimer.IsEnabled && _messages.Count > 0)
                _msgTimer.Start();
        }

        /// <summary>set permament operation text and start progress indeterminate</summary>
        public static void StartOperation(string name)
        {
            SetTextAndStop(name);
            StartIndeterminate();
        }

        /// <summary>Stop any progress and resume message queue</summary>
        public static void StopOperation(string result="")
        {
            StopProgress();
            SetText(result);
            Resume();
        }

        static void _msgTimer_Tick(object sender, object e)
        {
            if (_messages.Count > 0)
            {
                SetText(_messages.Dequeue());
            }
            else
            {
                _msgTimer.Stop();
                SetText(string.Empty);
            }
        }

        private static void SetText(string text)
        {
            _statusBar.ProgressIndicator.Text = text;
        }
    }
}

Example:

            Info.Init();
            Info.Add("Hello");  // Показываем Hello
            Info.Add("World");  // Добавляем в очередь сообщений World
            Info.QuickInform("Some Message"); // Затираем World, Выводим Some Message
// Через 5 сек. показываем World

Прочая информация в комментариях, как водится на ломанном английском 😉

 

MSDN: StatusBar in Windows Phone 8.1

Some Guy: Status Bar in Windows Phone 8.1

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *