如何在带有 XAML Islands 的 WPF 中使用 Windows 10 样式资源

How to use Windows 10 style resource in WPF with XAML Islands

我正在使用 XAML Islands 制作我的应用程序,我想在我的 WPF 应用程序中使用 Windows 10 种样式,例如 here。例如 <TextBlock Text="Header" Style="{StaticResource HeaderTextBlockStyle}"/> 将导致:

但这在 WPF 中不起作用(无需任何修改就可在 UWP 中起作用),我的理解是 XAML Islands 应该使它成为可能。当我尝试简单地将上面的代码添加到我的 xaml 文件时,我得到了异常

Cannot find resource named 'HeaderTextBlockStyle'. Resource names are case sensitive.

如果我将 Style="{StaticResource HeaderTextBlockStyle}" 添加到 <xamlhost:WindowsXamlHost> 元素,我会得到同样的异常。

所以我尝试用代码添加控件,所以我添加了这个 WindowsXamlHost 控件作为堆栈面板:

<xamlhost:WindowsXamlHost InitialTypeName="Windows.UI.Xaml.Controls.StackPanel" ChildChanged="WindowsXamlHost_ChildChanged"/>

并添加了此方法(一个事件处理程序,在创建控件时是 运行。从 this 中学习)处理向 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' resource not found.'

那么如何在我的 WPF 应用程序中获取这些样式资源呢?

实现此目的的一种方法是使用包 ModernWPF 但这样你就失去了 XAML 群岛的所有好处(如果有的话。我需要从 XAML 群岛获得的一切在 ModernWPF 中并且更容易实现)。

安装和设置 ModernWPF 后,您可以简单地使用 <TextBlock Text="Header" Style="{StaticResource HeaderTextBlockStyle}"/> 方法,它就可以正常工作。