本文介绍了如何使变量的值跟踪另一个变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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


推荐答案

Settings 类实现自定义的 EventHandler SettingsChangedEventHandler ),用于通知属性更改订阅者:

您可以设置更复杂的自定义 SettingsEventArgs 来传递不同的值。

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.

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

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

PhrasesFrame 类可以照常订阅事件:

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

这篇关于如何使变量的值跟踪另一个变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:03