【问题标题】:setting the MainWindow.Background to an external resource将 MainWindow.Background 设置为外部资源
【发布时间】:2013-03-16 03:38:55
【问题描述】:

我有一个包含主题“引擎”的 .dll。我几乎用一个内置的组合框完成了这个引擎,该组合框处理通过 .dll 切换主题。简而言之,我想要完成的是一个独立的 .dll,我可以从任何项目中引用它并且(无需向托管应用程序添加任何代码)拥有我的主题、样式等...

到目前为止,这可行,但我遇到了一点困境。由于 .dll 在运行时使用 URI 语法加载必要的 xaml 文件,因此托管应用程序控件本身在加载应用程序之前不知道资源。现在这会生成一个编译时警告,但在运行应用程序时没有问题。

我的问题与这个编译时问题有关。如果在运行时之前无法查看 .dll 中可用的画笔,如何设置主窗口的背景颜色?

<Window x:Class="Check.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mycon="clr-namespace:ThemeLibrary.MyControls;assembly=ThemeLibrary"
    Title="MainWindow" Height="350" Width="525" WindowStyle="None" AllowsTransparency="True" 
Background="{***DynamicResource ResourceKey=TransparentColorBrush***}">

同样,尽管存在错误,但程序编译并运行良好,因为如果无法解析动态资源,则窗口只是默认设置,但是一旦 .dll 加载包含键为 TransparentColorBrush 的画笔的资源字典,则窗口背景适当地改变。但是,如果我将我的 .dll 交给公众玩,他们将不知道不同的刷子键是什么,因此将无法进行此 hack。

那么,如何在 .dll 中设置 Application.Current.MainWindow.Background =(来自 URI 加载的资源字典或字典本身的画笔),或者 将画笔的键公开为公共属性?

【问题讨论】:

    标签: wpf styles themes resourcedictionary skinning


    【解决方案1】:

    好的,这就是我发现的...

    在我的 .dll 中,我可以通过简单地使用以下语法为应用程序窗口设置以下属性...

    Application.Current.MainWindow.SetResourceReference(Window.BackgroundProperty, "MainWindowBackgroundBrush");
            Application.Current.MainWindow.SetResourceReference(Window.BorderBrushProperty, "BorderBrush");
            Application.Current.MainWindow.SetResourceReference(Window.BorderThicknessProperty, "MainBorderThickness");
            Application.Current.MainWindow.SetResourceReference(Window.AllowsTransparencyProperty, "MainAllowsTransparency");
    

    在我创建的静态类中帮助管理皮肤变化的交互。我还声明了一个新的资源字典,如下所示:

    xmlns:s="clr-namespace:System;assembly=mscorlib"
    <Thickness x:Key="MainBorderThickness" >2</Thickness>
    <s:Boolean x:Key="MainAllowsTransparency">True</s:Boolean>
    

    我超级兴奋!!!这正是我一直在寻找的。因此,现在我的自定义皮肤和将它们从一种更改为另一种的机制都封装在一个 .dll 中,该 dll 可以处理与皮肤有关的所有事情,而无需向托管应用程序添加单个代码字符。现在每个 File>New 都可以简单地拥有一个程序集引用和 xmlns 命名空间,并且 POOF 我所有的皮肤都可用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多