2017-12-03 358 views
1

我在网格中有一个Image,我通过将图像源设置为WritableBitmap并更新位图来显示一些自定义内容。我想要做的是实现一个“分离”按钮,将我的图像放在一个单独的窗口允许用户将其移动到不同的屏幕,调整大小等独立于我的主要应用程序窗口。如果新窗口关闭,我想将它恢复到原来的位置。当图像位于新窗口中时,我想通过更新源位图来持续更新新内容(就像它在分离之前一样)。在UWP应用程序中实现可拆卸面板

我最初认为我可以创建一个新窗口,并通过首先将其从原始父项中移除,然后将其作为子项添加到新窗口中的布局中,从而“移动”我的图像控件。我用下面的代码:

CoreApplicationView^ newCoreView = CoreApplication::CreateNewView(); 
int mainViewId = Windows::UI::ViewManagement::ApplicationView::GetApplicationViewIdForWindow(
    CoreApplication::MainView->CoreWindow); 

uint indexOfObjectToDetach = -1; 
bool found = originalGrid->Children->IndexOf(imageToMove, &indexOfObjectToDetach); 
if(found) 
{ 
    myGrid->Children->RemoveAt(indexOfObjectToDetach); 
} 

DispatchedHandler^ dispatchHandler = ref new DispatchedHandler([this, mainViewId]() 
{ 
    newView_ = Windows::UI::ViewManagement::ApplicationView::GetForCurrentView(); 
    Windows::UI::Xaml::Controls::StackPanel^ newWindowGrid = ref new Windows::UI::Xaml::Controls::StackPanel(); 
    Window::Current->Content = newWindowGrid; 
    Window::Current->Activate(); 

    newWindowGrid->Children->Append(imageToMove); // Add to new parent 
}); 

create_task(newCoreView->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, dispatchHandler)).then([this, mainViewId]() 
{ 
    auto a = newView_->Id; 
    create_task(ApplicationViewSwitcher::TryShowAsStandaloneAsync(a, ViewSizePreference::Default, mainViewId, ViewSizePreference::Default)); 
}); 

但是在我的图像添加到其新的父行,我得到一个Interface was marshalled for a different thread错误。更多阅读时,这是由于每个新窗口都在自己的线程中,而我正在将对象移动到另一个线程。

我是UWP的新手,我不确定如何实现此UI行为。我如何在一个视图中访问/转移状态到另一个视图?

回答

1

问题的确是,UWP中的每个应用程序视图都有自己的线程和自己的UI调度程序。当你创建一个控件时,它被绑定到它创建的UI线程上,因此你不能把它放到另一个应用程序视图上。

解决方案是在新视图的UI线程内创建StackPanel旁边的新Image。我真的不使用C++,但在C#如下我会实现它:

await newCoreView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,() => 
    { 
     StackPanel panel = new StackPanel(); 
     Image image = new Image(); 
     panel.Children.Add(panel); 
     image.Source = ...; //your source 
     Window.Current.Content = frame; 
     Window.Current.Activate(); 
     newViewId = ApplicationView.GetForCurrentView().Id; 
    }); 

为了进一步澄清 - 你可以安全地“转移”正常的数据类型转换成另一种观点,问题主要是与用户界面 - 捆绑类型如控件,页面等。

相关问题