gpt4 book ai didi

c# - 检测何时设置了 Application.Current.RootVisual (Silverlight)

转载 作者:太空宇宙 更新时间:2023-11-03 13:20:02 26 4
gpt4 key购买 nike

假设我正在为 Windows Phone 应用程序 (Silverlight) 制作程序集(WindowsPhoneClassLibrary 或 PortableClassLibrary)。

有没有办法让我自动检测/注册/订阅 Application.Current.RootVisual 不为空的时刻?

我目前(由于异常而无法工作)的方法是:

var rootVisualTask = new TaskCompletionSource<UIElement>();
var application = Application.Current;
TaskEx.Run(() =>
{
while (application.RootVisual == null)
Thread.Sleep(1);
rootVisualTask.TrySetResult(application.RootVisual);
});
var rootVisual = await rootVisualTask.Task;

编辑

回答 McGarnagle 以解释我的程序集通常是如何初始化的。

在 App.xaml.cs 中:

static readonly PhoneApplicationFrame RootFrame = new PhoneApplicationFrame();
public App()
{
InitializeComponent();
RootFrame.Navigated += RootFrame_Navigated;
}
void RootFrame_Navigated(object sender, NavigationEventArgs e)
{
RootVisual = RootFrame;
RootFrame.Navigated -= RootFrame_Navigated;
}
void Application_Launching(object sender, LaunchingEventArgs e)
{
MyPlugin.Start();
}
void Application_Activated(object sender, ActivatedEventArgs e)
{
MyPlugin.Start();
}

事情按这个顺序发生:

  1. Application.Startup(未使用)
  2. Application.Launching(插件启动)
  3. RootFrame.Navigated(设置了 RootVisual,但 RootFrame 是私有(private)的)

我可能需要在 RootVisual = ... 之后手动插入 MyPlugin.HeyRootVisualIsSetAndNowYouCanUseIt(),但我试图避免这种情况。

编辑

与 Obj-C 不同,KVO is not implementable on Fields/Properties you don't own .这意味着可能没有人会找到更好的解决方案。

最佳答案

经过几个小时的试验,我发现这个工作正常:

var dispatcher = Deployment.Current.Dispatcher;
var application = Application.Current;
UIElement rootVisual = null;
while (rootVisual == null)
{
var taskCompletionSource = new TaskCompletionSource<UIElement>();
dispatcher.BeginInvoke(() =>
taskCompletionSource.TrySetResult(application.RootVisual));
rootVisual = await taskCompletionSource.Task;
}

我的问题循环中的 Thread.Sleep(1); 被替换为调用 Deployment.Current.Dispatcher.BeginInvoke() 以避免出现异常抛出。

关于c# - 检测何时设置了 Application.Current.RootVisual (Silverlight),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24653783/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com