c# - 如何在 WPF 中通过 XAML 岛使用 Windows 10 样式资源
问题描述
我正在使用 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 应用程序中获取这些样式资源呢?
解决方案
实现此目的的一种方法是使用包ModernWPF,但随后您将失去 XAML Islands 的所有好处(如果有的话。我需要的 XAML Islands 的一切都在 ModernWPF 中,并且更易于实现)。
安装和设置 ModernWPF 后,您可以简单地使用该<TextBlock Text="Header" Style="{StaticResource HeaderTextBlockStyle}"/>
方式,它就可以工作。
推荐阅读
- r - 如何在 R 中成功下载 ROCR
- c# - 基于TableName动态获取实体模型?
- java - 重用自定义异常信息
- javascript - JS 脚本不适用于使用 jQuery 的 .load() 加载的 div
- c# - 登录后 StaticInjectorError(AppModule)[AuthGuard]
- python - 连接两个数据框并根据条件删除重复行
- php - 如何通过 Docker 在 FSL Fresh Squeezed Limonade PHP Framework 中启用 SSL?
- android - 没有枚举常量 Facebook EventBinding.MappingMethod.BUTTON_INDEXING
- javascript - 带有样式组件的 cssjanus @noflip
- swing - JFrame does not show anything