我做了一个简单的UWP应用程序,与网络设备通信。我实现了一个异步方法await GetStatus("PW?")
,它发送特定的命令并返回设备的状态。另一方面,我需要在加载应用程序时实现SetPowerButtonProperties()
方法,这样我就可以在呈现UI后设置特定按钮的内容和颜色。我添加了Debug.WriteLine("yes");
,只是为了查看是否确实调用了该方法。我需要把这个方法放在哪里?
public async void SetPowerButtonProperties()
{
if (await GetStatus("PW?") == "PWON")
{
Debug.WriteLine("yes");
powerButton.Content = "Power OFF";
powerButton.Background = new SolidColorBrush(Colors.DarkRed);
}
else
{
Debug.WriteLine("no");
powerButton.Content = "Power ON";
powerButton.Background = new SolidColorBrush(Colors.DarkGreen);
}
}
我尝试在App.xaml.cs
中初始化一个MainPage
类,这样我就可以访问SetPowerButtonProperties()
方法和按钮的x:Name
:
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
var mainPage = new MainPage();
mainPage.SetPowerButtonProperties();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
Window.Current.Activate();
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
}
在本例中,在UI呈现后,输出结果为“yes”,这表示方法确实被调用了,但按钮的内容和颜色没有改变。注意,我还将MainPage.xaml
中的x:FieldModifier="public"
设置为public,因为一开始我得到了一个错误。<Button Content="Power ON" x:Name="powerButton" Click="PowerButtonClick" FontSize="20" x:FieldModifier="public"/>
1条答案
按热度按时间hi3rlvi21#
在UWP中,Page示例是通过
Frame.Navigate
方法示例化的。因此,你的方法不起作用。或者,您可以使用
Page.OnNavigatedTo
方法对Page示例执行某些操作。此外,如果您想将一些数据(字符串、字符、数字或GUID)从App传递到Page,则可以使用Frame.Navigate(TypeName,Object)方法的paramater
。App.xaml.cs
MainPage.xaml.cs