locked
Loading styles from a customcontrol class library via reflection, OnApplyTemplate is not called? RRS feed

  • Question

  • I am trying to load a custom control library via reflection in windows 8 Metro C# App, the library is loaded but the styles specified in generic.xaml are not loaded, eventually I tried to load the generic.xaml by making it as an Embedded resource and ,then extracted the Generic.xaml to a location and supplied it as uri of a ResourceDictionary object, but it throws an error "Failed to create a 'System.Type' from the text local:CustomControl1" , I cannot create a nuget package or extension SDK as unfortunately that is not my requirement,  Below sample code I wrote to copy the generic.xaml and load it in a resource dictionary.

    public sealed class CustomControl1 : Control
    {
       
    public CustomControl1()
       
    {
           
    this.DefaultStyleKey = typeof(CustomControl1);
           
    Assembly CurrentAssembly = typeof(CustomControl1).GetTypeInfo().Assembly;
           
    var names = CurrentAssembly.GetManifestResourceNames();
           
    var stream = CurrentAssembly.GetManifestResourceStream(names.First());
           
    //generic.xaml is an embedded resource in the current assembly
           
    if (stream != null)
           
    {
               
    //created new generic.xaml here
               
    var file = ApplicationData.Current.LocalFolder.CreateFileAsync("Generic.xaml", CreationCollisionOption.ReplaceExisting).Completed = (o, a) =>
               
    {
                   
    var storageFile = o.GetResults();

                   
    var s = storageFile.OpenStreamForWriteAsync().Result;

                   
    var length = (int)stream.Length;
                   
    byte[] bytes = new byte[length];
                   
    int output = stream.Read(bytes, 0, length);

                    s
    .Write(bytes, 0, length);
                    s
    .Flush();
                    s
    .Dispose();

                   
    var asyncResult = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                   
    {
                       
    var resourceDict = new ResourceDictionary();
                       
    var uri = new Uri("ms-appdata:///local/" + storageFile.Name);
                        resourceDict
    .Source = uri;
                   
    });
               
    };
           
    }
       
    }


       
    // OnApplyTemplate is not called without loading the style from generic.xaml
       
    protected override void OnApplyTemplate()
       
    {
           
    base.OnApplyTemplate();
       
    }
    }

    The below code I wrote in the custom control library's constructor, so that the control template can be set without generic.xaml

    Here since the attribute TargeType="local:CustomControl1" is not present the control gets loaded properly, here since I loaded the style in the constructor, the OnApplyTemplate gets called

    StringBuilder sb = new StringBuilder();
    sb
    .Append(@"<ControlTemplate 
    xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""  
    xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"" 
    xmlns:d=""http://schemas.microsoft.com/expression/blend/2008""
    xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"">"
    );
    sb
    .Append(@"<Border Background=""{TemplateBinding
    Background}""                                                            
    BorderBrush=""{TemplateBinding BorderBrush}""
    BorderThickness=""{TemplateBinding BorderThickness}"">
       <Grid>
          <Button x:Name=""Tbx1"" Content=""Hello World"" Foreground=""HotPink""  
           HorizontalAlignment=""Stretch"" VerticalAlignment=""Stretch""/>
      </Grid>
    </Border>"
    );
    sb
    .Append(@"</ControlTemplate>");
    this.Template = (ControlTemplate)XamlReader.Load(sb.ToString());

    but the problem is loading all the styles using XamlReader does not seem to be a good idea. As there may be various dependent styles which too have to be loaded.

    I am looking to distribute my customcontrol and the user should be able to use it with supporting assets such as images localization files and styles in a separate folder, Has anyone done this before for windows store apps?


    Wednesday, February 5, 2014 5:56 PM

All replies

  • Hi Abhishek,

    I did not understand where in your App you are using reflection by yourself to do what have said in your question.

    It appears to me you have an alternate and recommended way to do it refer Building a deployable custom control for XAML Metro style apps This is an old blog which will need some changes in present context but is good one to explain how to do it.

    Let me know if you still face issues. 


    -- Vishal Kaushik --

    Please 'Mark as Answer' if my post answers your question and 'Vote as Helpful' if it helps you. Happy Coding!!!

    Tuesday, February 25, 2014 3:05 AM