5

如果 App.xaml 位于与视图不同的程序集中,则此问题涉及 Visual Studio (2008) WPF 设计器明显无法处理位于 App.xaml 级别的资源的使用。

为了简化对问题的解释,我创建了一个测试应用程序。此应用程序有两个程序集:查看和启动。View 程序集包含一个名为 Window1 的 xaml 窗口,而 Start 程序集包含 App.xaml 文件。Start 程序集中的 App.xaml 文件将其 StartupUri 设置为 View 程序集中的 Window1。这些文件都没有代码隐藏(除了标准构造函数和 InitializeComponent() 调用)。

此示例的代码如下:

应用程序.xaml:

<Application x:Class="Start.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="pack://application:,,,/View;component/Window1.xaml"
         >
<Application.Resources> 

    <!-- Warning Text Style -->
    <Style x:Key="WarningTextStyle" TargetType="TextBlock">
        <Setter Property="FontWeight" Value="Bold" />
    </Style>

</Application.Resources>

Window1.xaml:

<Window x:Class="View.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" 
    Height="300" 
    Width="300"
    >

    <Grid>
        <TextBlock Text="This is test text" Style="{StaticResource WarningTextStyle}" />
    </Grid>
</Window>

Window1.xaml 文件包含一个引用应用级WarningTextStyle 的TextBlock。此代码在运行时运行良好,因为 Window 正确找到了 App 级资源;然而,在设计时,设计师抱怨它找不到WarningTextStyle。

有人知道这个问题的干净且可扩展的解决方案吗?

我对大型应用程序的标准方法是将我的应用程序级资源组织到资源字典文件中,然后将这些字典合并到 App.xaml 中。要解决我上面描述的问题,我必须将这些资源字典合并到每个视图的资源中。这似乎非常低效,如果我稍后添加另一个资源字典,那么我需要将该新字典合并到每个视图中。

一个灵丹妙药的解决方案将重新引导设计人员找到应用级资源。一个合理的解决方法是将应用程序级资源字典合并到每个视图中,但仅限于设计时。在运行时,由于效率问题,我想避免在每个视图中合并这些字典。

我尝试在视图的代码隐藏构造函数中合并每个视图上的字典,然后将该逻辑包装在检查 DesignerProperties.GetIsInDesignMode() 方法的 if 语句中;但是,Visual Studio 设计器不运行视图的构造函数 - 所以这种方法似乎是失败的。

有没有人有更好的解决方案或解决方法?

4

2 回答 2

2

您能否从您的主 (exe) 程序集的 App.xaml 中合并您引用的程序集中的资源字典(无论是 App.xaml 还是您自己的资源字典)?

于 2009-07-30T12:11:14.740 回答
1

我只是有一个不同的想法:使用动态资源而不是静态资源。这可能会对性能造成很小的影响,但我怀疑它是否可以衡量。

于 2009-07-30T12:54:29.370 回答