从另一个类更新UI控件

时间:2017-04-07 12:29:37

标签: c# signalr

我使用SignalR实现通知系统以在我的应用程序实例之间交换信息。我有以下集线器类:

[HubName("OpenHub")]
public class OpenHub:Hub
{
    public void DetermineLength(string message)
    {
        Clients.All.RecieveNewInfo(newMessage);
        //How to use something like the following line?
        //concerning that Form1 is loaded at application startup
        //and I should not create a new instance
        //Form1.lstMessages.Add(newMessage);
    }
}

然而,我必须更新一些UI控件,包括标签和列表框,以记录已到达的任何新信息。除了在我的表单代码中定义我的类之外,当我在不同的类中定义我的集线器时,如何更新Form对象以显示这些新信息?

2 个答案:

答案 0 :(得分:1)

如果您的应用是winform,您可以使用以下内容注册到集线器:

<?php
$servername = "localhost";
$username = "root";
$password = "root123";
$dbname = "test";

$AdName=[];
$TotalView=[];
$TotalMaleView=[];
$TotalFemaleView=[];
$rowcount=0;

// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
} 

$result=mysqli_query($con,"SELECT `Ad Name`,`Total View Count`, `Total Female Viewers`, `Total Male Viewers` FROM `addata` WHERE `Disp Id`=1");

$rowcount=mysqli_num_rows($result);

if(!$result) {
      die('Could not get data: ' . mysql_error());
    }
    // output data of each row 
    for($x = 0; $x < $rowcount; $x++)
    {
        $row = $result->fetch_assoc();
        $TotalView[$x]=$row["Total View Count"];
        $TotalFemaleView[$x]=$row["Total Female Viewers"];
        $TotalMaleView[$x]=$row["Total Male Viewers"];
        $AdName[$x]=$row["Ad Name"];
    }

$con->close();
?>
<html>
  <body>

    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <ul id="stats"></ul>
    <script type="text/javascript">

    var array1 = <?php echo json_encode($TotalView);?>;
    var array2 = <?php echo json_encode($TotalFemaleView);?>;
    var array3 = <?php echo json_encode($TotalMaleView);?>;
    var array4 = <?php echo json_encode($AdName);?>;

    google.charts.load('current', 
    { callback: function () 
        {   
            for ( y = 0; y < <?php echo $rowcount ?>; y++) 
            {

                var data = new google.visualization.DataTable();
                data.addColumn('string', 'list');
                data.addColumn('number', 'Viewers');
                data.addRows([ 
                                ['TotalViewers',array1[y]],
                                ['Female Viewers', array2[y]],
                                ['Male Viewers', array3[y]]
                            ]);
                var options = {title:array4[y],width:400,height:300};

                var container = document.getElementById('stats').appendChild(document.createElement('div'));
                var chart = new google.visualization.ColumnChart(container);
                chart.draw(data, options);
            }
        },
        packages: ['corechart']
    });

</script>
  </body>

</html>

使用HubProxy所需的命名空间是var Connection = new HubConnection("yourSignalRServerUrl"); var HubProxy = Connection.CreateHubProxy("OpenHub"); HubProxy.On<string>("RecieveNewInfo", (message) => this.Invoke((Action)(() => Form1.lstMessages.Add(message); ); await Connection.Start();

此示例来自:https://code.msdn.microsoft.com/windowsdesktop/Using-SignalR-in-WinForms-f1ec847b

答案 1 :(得分:0)

您可以在Program类或Form1类中使用公共静态属性来保存它的参考。

例如,在您使用Program

之前Application.Run(new Form1());

你可以这样做:

public static Form1 MainForm { get; set; }  

然后在Main()

MainForm = new Form1(); 
Application.Run(MainForm); 

从中心您可以立即访问您的表单:

[HubName("OpenHub")]
public class OpenHub:Hub
{
    public void DetermineLength(string message)
    {
        Clients.All.RecieveNewInfo(newMessage);

        Program.MainForm.lstMessages.Add(newMessage);
    }
}   

当然,lstMessages应该是公开的。或者你在表格中公开一些与之沟通的公共方法。