在C#中,ResourceManager
類用于管理應用程序中的文本資源。要實現(xiàn) ResourceManager
的動態(tài)加載,您需要遵循以下步驟:
ResourceDictionary
類,用于存儲和管理資源。public class CustomResourceDictionary : ResourceDictionary
{
public void LoadResources(string resourceName)
{
base.Source = new Uri($"pack://application:,,,/{resourceName}.xaml");
}
}
CustomResources.xaml
,并在其中定義您的資源。<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<System.Windows.Media.FontFamily x:Key="CustomFontFamily">Arial</System.Windows.Media.FontFamily>
<Style x:Key="CustomStyle" TargetType="Button">
<Setter Property="FontFamily" Value="{StaticResource CustomFontFamily}" />
</Style>
</ResourceDictionary>
CustomResourceDictionary
實例,并使用 LoadResources
方法動態(tài)加載資源。public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var customResourceDictionary = new CustomResourceDictionary();
customResourceDictionary.LoadResources("CustomResources");
this.Resources.MergedDictionaries.Add(customResourceDictionary);
}
}
現(xiàn)在,您可以在應用程序中使用已加載的資源,例如:
<Button Style="{StaticResource CustomStyle}">Click me</Button>
這樣,您就可以在運行時動態(tài)加載和使用 ResourceManager
中的資源了。