我制作了一个与网络设备通信的简单 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);
}
}
我尝试在
MainPage
中启动 App.xaml.cs
类,以便我可以访问 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”,这表明确实调用了该方法,但按钮的内容和颜色没有更改。请注意,我还将
x:FieldModifier="public"
中的 MainPage.xaml
设置为 public,因为一开始我收到了错误。
<Button Content="Power ON" x:Name="powerButton" Click="PowerButtonClick" FontSize="20" x:FieldModifier="public"/>
在 UWP 中,Page 实例是通过
Frame.Navigate
方法实例化的。因此你的方法不起作用。
或者,您可以利用
Page.OnNavigatedTo
方法对 Page 实例执行某些操作。此外,如果您想将一些数据(字符串、字符、数字或 GUID)从 App 移交给页面,您可以使用 Navigate(TypeName, Object)方法的
paramater
。
应用程序.xaml.cs
sealed partial class App : Application
{
...
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
...
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
var parameter = "data to be handed over";
rootFrame.Navigate(typeof(MainPage), parameter);
}
Window.Current.Activate();
}
}
...
}
MainPage.xaml.cs
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private bool isFirst = true;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (isFirst)
{
isFirst = false;
var parameter = e.Parameter; // "data to be handed over"
// Do something.
}
base.OnNavigatedTo(e);
}
}