UWP访问来自另一个类的参数



Hello all我目前正在开发一个UWP应用程序,其中包含TCP服务器以及其他一些功能。我开发了一种改变背景颜色的方法,通过修改Mainpage.Caml.cs中的1个值,代码显示在这里:

public sealed partial class MainPage : Page
{
public Windows.UI.Color backgroundColor;
public MainPage()
{
this.InitializeComponent();
BackgroundColor = Windows.UI.Color.FromArgb(255, 255, 255, 255);
MainConnection connector = new MainConnection();
connector.StartConnection("0.0.0.0", "10500");
}
public Windows.UI.Color BackgroundColor
{
get => backgroundColor;
set => backgroundColor = value;
}
}

我还使用getter和setter作为backgroundColor。正如您所看到的,我有另一个类,称为ConnectionClass,它处理连接并获取操作指令。ConnectionClass基于MSDN中可用的公共示例:

class MainConnection
{
private bool connectionAllowed = true;
public async void StartConnection(string net_aadress, string port_nr)
{
Windows.UI.Color backgroundColor;
backgroundColor = ChangeBackground(255, 255, 255);
try
{
var streamSocketListener = new StreamSocketListener();
// The ConnectionReceived event is raised when connections are received.
streamSocketListener.ConnectionReceived += this.StreamSocketListener_ConnectionReceived;
// Start listening for incoming TCP connections on the specified port. You can specify any port that's not currently in use.
await streamSocketListener.BindServiceNameAsync(port_nr);
Debug.WriteLine("server is listening...");
//Mainpage.viewModel.BackgroundColor = Windows.UI.Color.FromArgb(255, 255, 0, 255);
}
catch (Exception ex)
{
Windows.Networking.Sockets.SocketErrorStatus webErrorStatus =
Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
Debug.WriteLine((webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message));
}
}
private async void StreamSocketListener_ConnectionReceived(
Windows.Networking.Sockets.StreamSocketListener sender,
Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
{
do
{
RecievePacket();
decodePacket(); //using switch case 
switch(command)
case endConnection:
connectionAllowed = false;
SendResponsePacket();
break;
case changeBackground:
//in here we find out that we have to set BackgroundColor to some other color. How can i pass R G and B values from here to main
SendResponsePacket();
break;
}
while(connectionAllowed == true)
}

Windows.UI.Color ChangeBackground(UInt16 r, UInt16 g, UInt16 b)
{
return Windows.UI.Color.FromArgb(255, (byte)r, (byte)g, (byte)b);
}
}

在ConnectionClass中,有一种情况,我们突然从解码数据包中发现,我们必须更改backgroundColor,但这种情况存在于MainPanel.xaml.cs中如何从我刚才指出的范围访问和更改该参数?

实现这一点的最佳方法是Connection类在发生错误时公开一个事件,然后MainPage可以为该事件注册一个处理程序,并在引发该事件时更改其颜色。这样,网络堆栈中的低级错误就不会与UI的高级属性紧密耦合(这将是一个糟糕的设计(。

如果您需要创建事件的帮助,请参阅MSDN 上的处理和引发事件

此外,字段backgroundColorpublic也没有意义——它应该是private,因为您有一个public属性getter/setter。您甚至可以完全省略该字段,而只依赖于自动实现的属性:

public Color BackgroundColor { get; set; }

相关内容

最新更新