Reputation: 213
I'm trying to load different resource dictionaries for different build configurations (Debug, Release,etc ....) in my Xamarin Forms app.
I have tried setting the source property at runtime, but it didn't work (throw an error for invalid uri)
public App()
{
InitializeComponent();
Device.SetFlags(new string[] { "Expander_Experimental", "Shapes_Experimental" });
mainResourceDict.Source = new Uri("ResourceDictionaries/WebtrieveRD.xaml");
}
I couldn't find a way to add compiler directive conditions in XAML. Is there any other way this can be done?
Upvotes: 0
Views: 751
Reputation: 213
Okay, so I figured out that the source for ResourceDictionary can be set only from XAML (As per Xamarin documentation). But it has a method called SetAndLoadSource
which is marked as For internal use by Xamarin Platform
but can still be used to set the source dynamically from the code behind. Here's a usage example:
#if DEBUG
var source = new Uri("ResourceDictionaries/DebugRD.xaml", UriKind.RelativeOrAbsolute);
mainResourceDict.SetAndLoadSource(source, "ResourceDictionaries/DebugRD.xaml", this.GetType().GetTypeInfo().Assembly, null);
#endif
Upvotes: 1
Reputation: 4210
So, after some research, I think this might solve your problem. In order to determine if you're in release or debug, you'll have to insert constants in your Build page of the project. You go to the project file (right click on the project) -> Configuration Properties -> Build -> Conditional Compilation Symbols and check the "define DEBUG" option. Now that you have that marked, you can use something like:
#if DEBUG
ExecDebugMethod();
#else
ExecReleaseMethod();
#endif
Now, before being able to load a dictionary file, you'll also need to perform the following "preparation" steps:
Now that you successfully determined if you're running in release or debug mode and the previous steps are completed, the code for each of the methods is displayed below, to load dynamically the dictionary you need for each build type:
ResourceDictionary dict = new ResourceDictionary();
System.Windows.Application.LoadComponent(dict,
new System.Uri("/MyNamespace;ResourceDictionaries/DebugXAML.xaml",
System.UriKind.Relative));
But pay attention as this way of giving the dictionary path is relative to your folder location. If this does not solve your problem or I understood it wrong, please tell me and I'll update my answer.
Upvotes: 1