WPF 中的 经典的ModelView 通知页面更新 UI

view model

------------------------------------------------------------------------------

using HPControls.Helper;

using System;

using System.ComponentModel;

using System.Threading;

using Xiaowei.Models;

using Xiaowei.Services;

using Xiaowei.Settings;

 

namespace Xiaowei.ViewModels

{

    public class MuteViewModel : INotifyPropertyChanged

    {

        public event PropertyChangedEventHandler PropertyChanged;

        public bool IsMuted

        {

            get { return LocalSettings.IsMuted; }

            set

            {

                if(LocalSettings.IsMuted != value)

                {

                    LocalSettings.IsMuted = value;

                    Property.Raise(this, PropertyChanged, "IsMuted");

                }

            }

        }

 

        public void Toggle()

        {

            _ = HPMetrics.Metrics.Track(LocalSettings.CustomerId, (int)HPMetrics.XwEventType.ClickButton,"MuteButton");

   

               IsMuted = !IsMuted;

 

            _ = ApplicationModel.Current.ToggleMute(IsMuted);

            if(IsMuted)

            {

                StateManager.SetAttachState(StateManager.AttachStateEnum.micOff);

            }

            else

            {

                StateManager.RemoveAttachState(StateManager.AttachStateEnum.micOff);

            }

            

        }

 

        public static MuteViewModel Get() => LazyInstance.Value;

 

        private MuteViewModel()

        {

            Property.Raise(this, PropertyChanged, "IsMuted");

            if (IsMuted)

            {

                StateManager.SetAttachState(StateManager.AttachStateEnum.micOff);

            }

            else

            {

                StateManager.RemoveAttachState(StateManager.AttachStateEnum.micOff);

            }

        }

        

        private static readonly Lazy<MuteViewModel> LazyInstance = new Lazy<MuteViewModel>(()=>

        {

            return new MuteViewModel();

        }, LazyThreadSafetyMode.ExecutionAndPublication);

    }

}

 

 

 

 

Property 类

------------------------------------------

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Windows.ApplicationModel.Core;

 

namespace HPControls.Helper

{

    public static class Property

    {

        public static void Raise(object sender, PropertyChangedEventHandler handler, string property)

        {

            Run.Invoke(CoreApplication.MainView.CoreWindow.Dispatcher, () =>

            {

                handler?.Invoke(sender, new PropertyChangedEventArgs(property));

            });

        }

    }

}

 

posted @ 2021-01-20 07:17  MaxBruce  阅读(568)  评论(0编辑  收藏  举报