如何在设计时加载 WPF 资源字典

Ulr*_*ler 8 .net wpf

我有一个 WPF 窗口,其中一些属性被定义为动态资源,如下所示:

<Window x:Class="LocSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        MinHeight="350" MinWidth="525"
        Title="{DynamicResource ResourceKey=ResId_Title}"
        FlowDirection="{DynamicResource ResId_FlowDirection_Default}" >
    <Grid>
       <Label Content="{DynamicResource ResId_FirstName}" />  
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

ResourceDictionary在运行时加载,以反映语言选择的用户。并使用户能够即时切换语言。

这在运行时工作正常,但在设计时,不显示资源定义的属性。我很清楚设计师不能展示它们,因为它们在设计时没有定义。

我需要一种ResourceDictionary在设计时加载默认值的方法,以便设计人员可以显示任何内容。

vit*_*vit 6

编辑:

在 Blend 中,您可以在这种情况下使用设计时资源字典文件。Visual Studio 可以读取该文件,但没有创建该文件的工具。但是,如果您不怕项目文件,则可以手动完成。

  1. 将文件 DesignTimeResources.xaml 添加到您的项目。
  2. 打开您的项目文件 (*.csproj) 并找到 DesignTimeResources.xaml 文件的注册。
  3. 将此注册替换为以下代码
<Page Include="Properties\DesignTimeResources.xaml" Condition="'$(DesignTime)'=='true' OR ('$(SolutionPath)'!='' AND Exists('$(SolutionPath)') AND '$(BuildingInsideVisualStudio)'!='true' AND '$(BuildingInsideExpressionBlend)'!='true')">
  <Generator>MSBuild:Compile</Generator>
  <SubType>Designer</SubType>
  <ContainsDesignTimeResources>true</ContainsDesignTimeResources>
</Page>
Run Code Online (Sandbox Code Playgroud)

现在您可以合并文件中所需的所有资源字典。编译器会忽略它,但设计器不会。

有关更多详细信息,请参阅我的文章

  • 对于 VS2019 项目文件: &lt;Page Update="Properties\DesignTimeResources.xaml"&gt; &lt;SubType&gt;Designer&lt;/SubType&gt; &lt;ContainsDesignTimeResources&gt;True&lt;/ContainsDesignTimeResources&gt; &lt;/Page&gt; (2认同)