![](/img/trans.png)
[英]How to use the correct WindowsRuntime.dll in WPF for XAML Islands?
[英]How to use Windows 10 style resource in WPF with XAML Islands
我正在使用 XAML Islands 來制作我的應用程序,我想在我的 WPF 應用程序中使用 Windows 10 樣式,就像這里一樣。 例如<TextBlock Text="Header" Style="{StaticResource HeaderTextBlockStyle}"/>
將導致:
但這在 WPF 中不起作用(它在 UWP 中起作用,無需任何修改),我的理解是 XAML Islands 應該使它成為可能。 當我嘗試簡單地將上面的代碼添加到我的 xaml 文件中時,我得到了異常
找不到名為“HeaderTextBlockStyle”的資源。 資源名稱區分大小寫。
如果我將Style="{StaticResource HeaderTextBlockStyle}"
添加到<xamlhost:WindowsXamlHost>
元素,我會得到相同的異常。
因此,我嘗試使用代碼添加控件,因此我將此 WindowsXamlHost 控件添加為堆棧面板:
<xamlhost:WindowsXamlHost InitialTypeName="Windows.UI.Xaml.Controls.StackPanel" ChildChanged="WindowsXamlHost_ChildChanged"/>
並添加了這個方法(一個在制作控件時運行的事件處理程序。從中學習), 它處理向 StackPanel 添加額外的控件(一個 TextBlock):
private void WindowsXamlHost_ChildChanged(object sender, EventArgs e)
{
// Get the host control
WindowsXamlHost host = (WindowsXamlHost)sender;
// Get the StackPanel in the host
Windows.UI.Xaml.Controls.StackPanel sp = (Windows.UI.Xaml.Controls.StackPanel)host.Child;
// Make a TextBlock to add to the StackPanel
Windows.UI.Xaml.Controls.TextBlock textBlock = new Windows.UI.Xaml.Controls.TextBlock();
// Set the text of the TextBlock
textBlock.Text = "LockCursorInMonitor";
// Get the style resources, cast them to the appropriate type for XAML Islands and add them to the TextBlock
textBlock.Style = (Windows.UI.Xaml.Style)Application.Current.Resources["HeaderTextBlockStyle"];
// Another way to get resources but this doesn't work too.
//textBlock.Style = (Windows.UI.Xaml.Style)this.FindResource("HeaderTextBlockStyle");
// Add the TextBlock to the stackpanel
sp.Children.Add(textBlock);
}
Application.Current.Resources["HeaderTextBlockStyle"]
方式什么都不做,也不會拋出異常。
this.FindResource("HeaderTextBlockStyle")
方式拋出下一個異常:
System.Windows.ResourceReferenceKeyNotFoundException: ''HeaderTextBlockStyle' 資源未找到。'
那么如何在我的 WPF 應用程序中獲取這些樣式資源?
實現此目的的一種方法是使用 package ModernWPF ,但隨后您將失去 XAML 群島的所有好處(如果有的話。我需要從 XAML 中獲得的一切。並且在現代 WPF 中更容易實現島嶼)
安裝和設置 ModernWPF 后,您可以簡單地使用<TextBlock Text="Header" Style="{StaticResource HeaderTextBlockStyle}"/>
方式,它就可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.