如何使变量的值跟踪另一个变量的值

时间:2018-10-07 03:36:46

标签: c#

这是我现在拥有的一个非常简化的示例:

public static class Settings
{
    public static TH th;
}

public partial class PhrasesFrame
{
    private void SetC1Btn()
    {
        var a = (int)Settings.th;
        vm.C1BtnLabelTextColor = phrase.C1 == true ?
            Styles.A[(int)Settings.th] :
            Styles.A[(int)Settings.th];
    }

我想替换为:

public partial class PhrasesFrame
{
    // The value of Settings.th can change at any time

    // I want the value of id to change when the 
    // value of (int)Setting.th changes. The way
    // it's coded now I realize it's just a one
    // time assignment

    var id = (int)Settings.th; 

    private void SetC1Btn()
    {
        var a = (int)Settings.th;
        vm.C1BtnLabelTextColor = phrase.C1 == true ?
            Styles.A[id] :
            Styles.A[id];
    }

2 个答案:

答案 0 :(得分:4)

Settings类实现了自定义EventHandlerSettingsChangedEventHandler),用于将属性更改通知其订阅者:
您可以设置更复杂的自定义SettingsEventArgs来传递不同的值。

更改公共THProperty属性值会引发以下事件:

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)); }
    }
}

PhrasesFrame类可以照常订阅事件:

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();
    }
}

答案 1 :(得分:2)

将动作添加到静态设置类,然后从设置器中触发该动作如何?

我使用了int而不是TH对象,但是我确定您可以改写以下示例。

在此处进行测试: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;
    }
}