Loading ResourceDictionary from code
Don't know why I couldn't get my head wrapped around this but after spending way to much time figuring it out from bits and pieces found while googling I thought it might be of benefit to others.
I have a Wpf control library that contains Custom controls that derive from System.Windows.Control and have no markup associated with them. I have also created a ResourceDictionary with a Style defined and when I create a control I want to dynamically assign this Style to it but since it has not been loaded am not able to access the style defined in the ResourceDictionary.
The solution is listed below;
///
/// Dynamically loads the dictionary from ganttWpfControl.dll.
///
private void LoadDictionary()
{
//Has to be a realtive Uri for the Load to work
Uri uri = new Uri("/ganttWpfControl;component/Resources/ItemDictionary.xaml", UriKind.Relative);
ResourceDictionary rd = Application.LoadComponent(uri) as ResourceDictionary;
Resources.MergedDictionaries.Add(rd);
}
public void AddItem(ganttItemControl item)
{
item.Style = (Style)Resources["ItemStyle"];
Children.Add(item);
}