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

前端 未结 2 1473
鱼传尺愫
鱼传尺愫 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:48

    How about adding an Action to your static Settings class, and firing that action from the th setter?

    I've used an int instead of your TH object, but I'm sure you can adapt the following example.

    Test it here: https://dotnetfiddle.net/ItaMhL

    using System;
    public class Program
    {
        public static void Main()
        {
            var id = (int)Settings.th;
            Settings.action = () => id = Settings.th;
            Settings.th = 123;
            Console.WriteLine(id);
    
            Settings.th = 234;
            Console.WriteLine(id);
        }
    
        public static class Settings
        {
            private static int _th;
            public static int th
            {
                get{return _th;}
                set{
                    _th = value;
                    action();}
            }
    
            public static Action action;
        }
    }
    
    0 讨论(0)
  • 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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题