1

I have a solution with multiple projects:

  • The Application
  • The User Control Library
  • The Class Library

I would like to apply a Style contained in the Class Library to the User Control contained in the User Control Library. The problem is that I can't reference the Style in the App.xaml like I would do with the main application because I'm working with a User Control Library and I don't know how let the User Control use the Class Library Styles. I added the Class Library reference to the User Control Library but when I set the Style for a User Control I cannot find the Style I want. So what is the current way to do it?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Belfed
  • 165
  • 1
  • 13

1 Answers1

0

You could use the following MarkupExtension. You just need to add both files to your class library.

WpfRdExt/StyleRefExtension.cs

public abstract class StyleRefExtension : MarkupExtension
{
    #region Fields

    /// <summary>
    /// Property for specific resource dictionary
    /// </summary>
    protected static ResourceDictionary RD;

    #endregion

    #region Properties

    /// <summary>
    /// Resource key which we want to extract
    /// </summary>
    public string ResourceKey { get; set; }

    #endregion

    #region Public Methods

    /// <summary>
    /// Overriding base function which will return key from RD
    /// </summary>
    /// <param name="serviceProvider">Not used</param>
    /// <returns>Object from RD</returns>
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return ProvideValue();
    }

    public object ProvideValue()
    {
        if (RD == null)
            throw new Exception(
                @"You should define RD before usage. 
            Please make it in static constructor of extending class!");
        return RD[ResourceKey];
    }

    #endregion
}

Implementation as StyleRefExt.cs:

public class StyleRefExt : StyleRefExtension
{
    #region Constructors

    static StyleRefExt()
    {
        RD = new ResourceDictionary {
                 Source = new Uri("pack://application:,,,/YourNamespace;component/Styles/YourStyle1.xaml")};

        RD.MergedDictionaries.Add(new ResourceDictionary {
                                      Source = new Uri(
                                          "pack://application:,,,/YourNamespace;component/Styles/YourStyle2.xaml")});
    }

    #endregion
}

Then you can use your Resources marked by x:Key="YourKey" from class library in your user control library like this:

<TextBox Style="{YourNamespace:StyleRefExt ResourceKey=YourKey}" />

For me this works fine and I use it too.

WPFGermany
  • 1,639
  • 2
  • 12
  • 30