How can I make the value of a variable track the value of another

前端 未结 2 1477
鱼传尺愫
鱼传尺愫 2020-12-02 02:43

Here\'s a very simplified example of what I have now:

public static class Settings
{
    public static TH th;
}

public partial class PhrasesFrame
{
    priv         


        
2条回答
  •  囚心锁ツ
    2020-12-02 02:51

    This Settings class implements a custom EventHandler (SettingsChangedEventHandler), used to notify a property change to its subscribers:
    You could setup a more complex custom SettingsEventArgs to pass on different values.

    Changing the public THProperty property value raises the event:

    public static class Settings
    {
        public delegate void SettingsChangedEventHandler(object sender, SettingsEventArgs e);
        public static event SettingsChangedEventHandler SettingsChanged;
    
        private static TH th;
        private static int m_Other;
    
        public class SettingsEventArgs : EventArgs
        {
            public SettingsEventArgs(TH m_v) => THValue = m_v;
            public TH THValue { get; private set; }
            public int Other => m_Other;
        }
    
        public static void OnSettingsChanged(SettingsEventArgs e) => 
            SettingsChanged?.Invoke("Settings", e);
    
        public static TH THProperty
        {
            get => th;
            set { th = value; OnSettingsChanged(new SettingsEventArgs(th)); }
        }
    }
    

    The PhrasesFrame class can subscribe the event as usual:

    public partial class PhrasesFrame
    {
        private TH id;
    
        public PhrasesFrame()
        {
            Settings.SettingsChanged += this.SettingsChanged;
        }
    
        private void SetC1Btn()
        {
            var a = (int)this.id;
            //Other operations
        }
    
        private void SettingsChanged(object sender, Settings.SettingsEventArgs e)
        {
            this.id = e.THValue;
            SetC1Btn();
        }
    }
    

提交回复
热议问题