简体   繁体   中英

Cant add ResourceDictionary to Application.Current.Resources.MergedDictionaries from xamarin.forms

I will explain in 3 basic steps what i do and then show the code:

  1. I read an asset from android project (using xamarin.forms)
  2. I receiv the textcontent to the multiplattform project where i want to use MVVM i then write the content to System.Environment.SpecialFolder.Personal folder
  3. I want to add it to Application.Current.Resources.MergedDictionaries by using an new uri from the text i wrote in step 2.

The problem- when i try to add it to the ResourceDictionary it says - : 'Source can only be set from XAML.'

Code:

1)

            string content;
        using (StreamReader sr = new StreamReader(Assets.Open(assetName)))
        {
            content = sr.ReadToEnd();
        }
  1. `

     private static string fileName { get; set; } public static void BeforeLoadForms(string colorsXAML) { var backingFile = Path.Combine(System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal), "colorsXAML.xaml"); using (var writer = File.CreateText(backingFile)) { writer.WriteLine(colorsXAML); } fileName = backingFile; }`
            Application.Current.Resources.MergedDictionaries.Clear(); 
            ResourceDictionary rd1 = new ResourceDictionary();
            rd1.Source = new Uri(fileName, UriKind.Absolute);

        Application.Current.Resources.MergedDictionaries.Add(rd1);

(Untested; I don't know if this will work.)

The error message says you can only set Source in XAML. First, try a manual test, where you use a file you've prepared beforehand.

Add to project a new item, a XAML file. Contents:

<ResourceDictionary
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    x:Class="MyNameSpace.MyResourceDictionary" Source="file:///myresources.xml"/>

Put in appropriate names in place of MyNameSpace, MyResourceDictionary, myresources.xml.

I'm not sure the exact form needed for a file URI.

Then in your code, where you currently try to add to Resources.MergedDictionaries, instead do:

var rd = new MyResourceDictionary();
Application.Current.Resources = rd;

If you can get this to work, then you can improve it. For example, could use MVVM, change to Source="{Binding ResourcesURI}" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM