Загрузка ресурсов в импортированную сборку
Я разработал для приложений программу планировщика и программу администрирования библиотеки. Библиотека admnistration нуждается в некоторых из тех же функций в программе планировщика, поэтому опубликовала программу планировщика в NuGet, установила ее в программе администрирования libray и использовала здесь пользовательские элементы управления из программного обеспечения планировщика. Это прекрасно работает, за исключением того, что переводы из планировщика не загружаются, когда я использую его в программе библиотеки. Он отлично работает, когда я использую программу планировщика самостоятельно.
В обеих программах я создал ResourceDictionary, как это
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cultures="clr-namespace:LibraryAdministration.Cultures">
<!-- Resources ODP contains the current instance of the WPFLocalize.Properties.Resources class.
Used in bindings to get localized strings and automatic updates when the culture is updated -->
<ObjectDataProvider x:Key="Resources" ObjectType="{x:Type cultures:CultureResources}" MethodName="GetResourceInstance"/>
<!-- CultureResources ODP provides access to list of currently available cultures -->
<ObjectDataProvider x:Key="CultureResourcesDS" ObjectType="{x:Type cultures:CultureResources}"/>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="pack://application:,,,/Administration;component/resourcedictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
Я загружаю ресурсы в обеих программах, как это
{Binding Path=MainWindow_Title, Source={StaticResource Resources}}
Это мой урок культуры в обоих приложениях
public class CultureResources
{
//only fetch installed cultures once
private static bool bFoundInstalledCultures = false;
private static List<CultureInfo> pSupportedCultures = new List<CultureInfo>();
/// <summary>
/// List of available cultures, enumerated at startup
/// </summary>
public static List<CultureInfo> SupportedCultures
{
get { return pSupportedCultures; }
}
public CultureResources()
{
if (!bFoundInstalledCultures)
{
//determine which cultures are available to this application
Debug.WriteLine("Get Installed cultures:");
CultureInfo tCulture = new CultureInfo("");
foreach (string dir in Directory.GetDirectories(Application.StartupPath))
{
try
{
//see if this directory corresponds to a valid culture name
DirectoryInfo dirinfo = new DirectoryInfo(dir);
tCulture = CultureInfo.GetCultureInfo(dirinfo.Name);
//determine if a resources dll exists in this directory that matches the executable name
if (dirinfo.GetFiles(Path.GetFileNameWithoutExtension(Application.ExecutablePath) + ".resources.dll").Length > 0)
{
pSupportedCultures.Add(tCulture);
Debug.WriteLine(string.Format(" Found Culture: {0} [{1}]", tCulture.DisplayName, tCulture.Name));
}
}
catch(ArgumentException) //ignore exceptions generated for any unrelated directories in the bin folder
{
}
}
bFoundInstalledCultures = true;
}
}
/// <summary>
/// The Resources ObjectDataProvider uses this method to get an instance of the WPFLocalize.Properties.Resources class
/// </summary>
/// <returns></returns>
public LibraryAdministration.Cultures.Resources GetResourceInstance()
{
return new Resources();
}
private static ObjectDataProvider m_provider;
public static ObjectDataProvider ResourceProvider
{
get
{
if (m_provider == null)
m_provider = (ObjectDataProvider)App.Current.FindResource("Resources");
return m_provider;
}
}
/// <summary>
/// Change the current culture used in the application.
/// If the desired culture is available all localized elements are updated.
/// </summary>
/// <param name="culture">Culture to change to</param>
public static void ChangeCulture(CultureInfo culture)
{
//remain on the current culture if the desired culture cannot be found
// - otherwise it would revert to the default resources set, which may or may not be desired.
if (pSupportedCultures.Contains(culture))
{
Resources.Culture = culture;
ResourceProvider.Refresh();
}
else
Debug.WriteLine(string.Format("Culture [{0}] not available", culture));
}
}
}
Я знаю, что проблема в том, что ресурсы в программном обеспечении планировщика не инициализированы, я попытался создать MergedDictionaries в моем приложении библиотеки, как это безуспешно
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="pack://application:,,,/Administration;component/resourcedictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
Надеюсь, есть кто-то, кто может помочь мне с этим.
Спасибо Андерс Миккельсен
1 ответ
Я решил это, добавив ObjectDataProvider в мой resourceDirectory.xaml в моей администрации библиотеки
<ObjectDataProvider x:Key="CSResources" ObjectType="{x:Type CScultures:CultureResources}" MethodName="GetResourceInstance"/>
от моей администрации schduler
"xmlns:CScultures="clr-namespace:Administration.Cultures;assembly=Administration"
Я назвал ключ так же, как и в моей администрации планировщика.
Поскольку не может быть двух ключей с одинаковым значением, я изменяю имя моего ресурса на CSResource.