我想将文件包含到程序集中,并在以后访问它。在这个例子中,我有两个主题。其中一个主题有这样的代码。这段代码确实有效。但是相对于可执行文件,我需要将资产放入构建输出中。
sakura.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="backColor" Color="Red" />
</ResourceDictionary>
项目.csproj
<ItemGroup>
<Content Include="assets/themes/ice_blue.xaml" />
<Content Include="assets/themes/sakura.xaml" />
</ItemGroup>
主窗口.xaml
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Rectangle
Grid.Row="0"
Height="50" Fill="{DynamicResource backColor}" />
<Button
Grid.Row="1"
Content="Change" Click="change_Color" />
</Grid>
在这段代码中,我在程序集外部加载sakura.xaml。.csproj
中的Content Include
似乎不起作用,或者我错误地使用了相对于程序集输出的Content-Include。如果输出构建是输出的。程序集将从output/assets/themes/sakura.xaml.加载
主窗口.cs
private void change_Color(object sender, RoutedEventArgs e)
{
Application app = Application.Current;
var resources = app.Resources.MergedDictionaries;
resources.Clear();
resources.Add(
new ResourceDictionary{
Source = new Uri("assets/themes/sakura.xaml", UriKind.Relative)
}
);
}
我要做的是使用XamlReader
从文件加载主题,使用MergedDictionaries
使主题在运行时可用。然后使用应用程序显式部署主题文件。
下面是一个清晰的例子:https://www.wpfsharp.com/2012/01/26/how-to-load-a-dictionarystyle-xaml-file-at-run-time/
这里的关键方法:
/// <summary>
/// This funtion loads a ResourceDictionary from a file at runtime
/// </summary>
public void LoadStyleDictionaryFromFile(string inFileName)
{
if (File.Exists(inFileName))
{
try
{
using (var fs = new FileStream(inFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
// Read in ResourceDictionary File
var dic = (ResourceDictionary)XamlReader.Load(fs);
// Clear any previous dictionaries loaded
Resources.MergedDictionaries.Clear();
// Add in newly loaded Resource Dictionary
Resources.MergedDictionaries.Add(dic);
}
}
catch
{
}
}
}