只显示信息/更新主gui的最佳方式

时间:2017-02-06 14:27:09

标签: c# class main solid-principles

首先,这可能是一个愚蠢/愚蠢的问题,但无论如何,这不是一个问题,基本上我正在搜索从类到主窗口显示结果的最佳方法。 现在我将告诉你我需要什么,然后我会用现有的知识解决这个问题,知道它的方法不正确,

enter image description here

所以点击按钮我这样做:

private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            new Notification().DoNotify(txtMessage.Text);
        }

类定义是:

public class Notification
    {
        private IMessenger _iMessenger;
        public Notification()
        {
            _iMessenger = new Email();
        }
        public void DoNotify(string Message)
        {
            _iMessenger.SendMessage(Message);
        }
    }

interface IMessenger
    {
        void SendMessage(string Message);
    }

public class SMS : IMessenger
    {
        public void SendMessage(string Message)
        {
            // i want code that will print this message variable to the txtSMS textbox.
        }
    }

    public class Email : IMessenger
    {
        public void SendMessage(string Message)
        {
            // i want code that will print this message variable to the txtEmail textbox.
        }
    }

现在如何从这些类更新主窗口GUI,

我将使用的一个解决方案是,在其中添加带有mainwindow对象的新tempclass,然后访问它,

public class TempClass
    {
        public static MainWindow Main;
    }
主窗口构造函数中的

public MainWindow()
        {
            InitializeComponent();
            TempClass.Main = this;
        }

和短信/电子邮件类:

public class Email : IMessenger
    {
        public void SendMessage(string Message)
        {
            TempClass.Main.txtEmail.Text = Message;
        }
    }

    public class SMS : IMessenger
    {
        public void SendMessage(string Message)
        {
            TempClass.Main.txtSMS.Text = Message;
        }
    }

现在这个有效,但是必须有一个更好的方法...你觉得什么,对不起长篇大论......:// 有关于此的任何原则或设计模式吗?

1 个答案:

答案 0 :(得分:0)

如果您的应用程序有两个或更多实例,则不建议使用静态属性。您可以在MainWindow中定义一个方法:

internal void SetMessage(string Message)
{
     Dispatcher.BeginInvoke(new Action(() => {txtSMS.Text = Message;}));
}

并将MainWindow的实例发送到其他类,无论是否由特定的构造函数

MainWindow parentWindow;
void btnSend_Click(object sender, RoutedEventArgs e)
{
      if (parentWindow != null)
          _parentWindow.SetMessage(txtMessage.Text);
}

或通过定义DependencyProperty并使用Binding。

您也可以使用事件,但我更喜欢上述内容。