第二类窗口上的C#WPF更新标签 [英] C# WPF Update label on window from 2nd class

查看:40
本文介绍了第二类窗口上的C#WPF更新标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里的新手,很抱歉这个愚蠢的问题,但是由于某种原因,我在这个简单的小问题上遇到了一个真正的问题.我在WPF窗口上有一个标签和按钮,我正在尝试从第二个静态class.cs代码文件更新标签.例如:
MainWindow.xaml.cs
内部静态命名空间.MainWindow myMainWindow;


Newbie here so sorry for the dumb question but I''m having a real problem with this simple little issue for some reason. I have a label and button on WPF window and I''m trying to update label from a 2nd static class.cs code file. For exmple:
MainWindow.xaml.cs
internal static namespace.MainWindow myMainWindow;


public delegate void Update_lbl1(string text);
public void refresh(string text)
{
if (lbl_1.Dispatcher.CheckAccess())
{     lbl_1.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Update_lbl1(refresh), text);
return;
}       
lbl_1.Content = text;
}
private void buttonKonekcija_Click(object sender, RoutedEventArgs e)
{
  class.start();
}



在我的class.cs中,我有:



in my class.cs i have:

public static void Start()
{
  try
   {        
MainWindow.myMainWindow.Dispatcher.BeginInvoke(new Action(delegate() { MainWindow.myMainWindow.lbl_1.Content = "Label text is change"; }));  
// have error here   Object reference not set to an instance of an object.    
   }
catch (Exception e)
 {
MainWindow.myMainWindow.Dispatcher.BeginInvoke(new Action(delegate() { MainWindow.myMainWindow.lbl_1.Content = e.message; })); 

}
}



我不明白为什么会这样,有人可以教我该怎么做.我正在寻找5天的时间来解决这个问题,但没有希望:((
谢谢



I don''t understand why this is happening, can someone please teach me how to do this right.I am searching 5 days to solve this problem and no hope :((
Thank you

推荐答案

正如您所说,这是一个相当简单的问题.只是您使它变得复杂而已.

看看 http://tap-source.com/?p=160 [
As you say, this is a fairly simple problem. It''s just that you''ve made it over complicated.

Take a look at http://tap-source.com/?p=160[^] to show you simple MVVM and binding. Get to know your ViewModels and they''ll make problems like this as trivial as they should be ;-)


据我了解,您正在尝试实现Singleton模板以访问主表单.而且看起来像关于myMainWindow的错误;

要正确执行此操作,请在MainWindow类中执行以下操作:
As far as I understand you are trying to implement Singleton template for accessing main form. And it looks like error about myMainWindow;

To do it right do the following in your MainWindow class:
private static MainWindow _instance = null;

public static MainWindow Instance
{
 get
 {
  if (_instance == null)
  {
   _instance = new MainWindow(); 
  }
  return _instance;
 }
}



然后在另一个类中,您可以像下面这样访问MainWindow的实例:



then in your another class you can access instance of MainWindow like this:

MainWindow.Instance.lbl_1.Content = "Label text is change";


这篇关于第二类窗口上的C#WPF更新标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆