【问题标题】:Refresh userControl from outside class从外部类刷新 userControl
【发布时间】:2014-06-09 21:12:58
【问题描述】:

我有一个显示来自数据库的结果数据的应用程序。有时,如果结果带有附加数据,那么我们会附加记录。在UserControl 中,值是“NA”,直到发生这种情况。我在UserControl 类中有一个refreshdisplay() 方法,效果很好,不幸的是,如果我在使用new 后从我的dataHandler 类调用它,UserControl 不会刷新。我猜这是因为我使用了

UserControlResultDisplay resultDisplay = new UserControlResultDisplay();

如何在不实例化新的情况下使用方法并与现有的 UserControl 交互?

这里有一些代码sn-ps:

UserControlResultDisplay resultDisplay = new UserControlResultDisplay();

public void UpdateResultDB(ResultDataJFTOT resultData)
{    
    AnalysisListCommon myresult = PContext.GetInstance().DbHandlerLocal.StoredResult(
        resultData.SampleId,
        resultData.TestDate.ToString("yyyy-MM-ddTHH:mm", CultureInfo.InvariantCulture),
        resultData.InstrumentSn,
        StringRepository.constStringSampleName);
    if (myresult != null)
    {
        Result r = new Result(new Guid(myresult.ResultId));
        ResultData rd = r.GetResultData("Rating", FindResultDataMode.byVariableIdentifier);
        string xmlTubeRating = resultData.tRating.ToString().Replace("#LT#", "<");
        rd.Text = xmlRating;
        rd.Store();
        rd = r.GetResultData("TestDate", FindResultDataMode.byVariableIdentifier);
        rd.Text = resultData.Date.ToString();
        rd.Store();
        resultDisplay.RefreshDisplay();
    }
    else
    {
        AddTestToQueue(resultData);
    }   
}

【问题讨论】:

  • 通过构造函数传入现有引用?这就是你通常的做法......我是否错过了阻止这种情况的东西?
  • 我这样做了,但是关键字“new”的使用似乎让我头晕目眩。这是否会打开 UserControl 的新实例,而不是使用打开的实例。调用函数不在窗体中,因此该函数在 UserControl 打开且可见时执行。我有点像菜鸟,所以如果我离基地很远,请耐心等待并详细说明。
  • 如果作为参数传入,则不需要new关键字。你能把代码贴在你这样做的地方吗?
  • @BradleyDotNet 那可能是我的问题。原谅我,因为我还是绿色的。但我认为 c# 中的对象不是值,不能传递。我很抱歉问了一些我应该知道的问题,但是......我该怎么做
  • 看看我的回答,希望它可以消除你的困惑 :)

标签: c# refresh


【解决方案1】:

正如你所指出的,问题出在声明中:

UserControlResultDisplay resultDisplay = new UserControlResultDisplay();

这会实例化一个新对象(与现有对象无关),因此在其上运行函数绝对不会影响 GUI 上显示的内容。

在我找到正确的代码之前,让我试着弄清楚什么是“对象”。

C# 中的每种类型,无论是显式还是隐式,都可以被视为“对象”(甚至是像 int 这样的值类型),因此这种区别在很大程度上是无关紧要的。但是,您说对象有两种分类是正确的:

  1. 值类型按值传递(并不奇怪),在创建过程中不需要/允许 new 关键字。这些是你的intfloatchar 等。
  2. reference 传递的引用类型,并使用new 关键字来创建它们。这些是用class 声明的任何东西(可能还有其他一些,但这是一个很好的经验法则)。

对于任何函数来说,两者都是完全可以接受的参数,只是它们的传递方式不同。对于您正在尝试做的事情,我们实际上利用了这一点。如果你写:

UserControlResultDisplay resultDisplay;

public MyDataClass(UserControlResultDisplay uiDisplay)
{
    resultDisplay = uiDisplay;
}

您正在获取(并存储)对现有 UI 对象的引用。现在,当你在上面调用函数时,它会影响 UI(当然,假设 UI 端的所有内容都设置正确)。你会像这样调用这个构造函数(假设它来自 UI 类):

MyDataClass data = new MyDataClass(this);

如果您在其他地方调用它,您显然需要从其他地方引用 UI 以传递给 MyDataClass

【讨论】:

    猜你喜欢
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 2014-06-29
    • 2014-01-11
    相关资源
    最近更新 更多