Ok so I know how to assign a data template to the legend's items. In XAML it's as easy as putting the data template for LegendItemTemplate in xamChart.Resources and setting Legend.UseDataTemplate = true.
But how do I do this in code behind? I've tried the following:
xamChart.Resources.Add(typeof(LegendItemTemplate), this.TryFindResource(typeof(LegendItemTemplate)));
xamChart.Resources.Add("itemTemplate", this.TryFindResource("itemTemplate"));
The resource is added to xamChart.Resources no worries but XamChart doesn't seem to be picking it up at all. If no theme is specified, the chart just shows the object name and if a theme is specified, it just shows the theme's default data template.
i couldn't figure this out either until I found the answer here: http://stackoverflow.com/questions/491195/what-key-to-use-if-adding-a-data-template-to-the-resources-of-a-control
you learn something new every day. here's the code i used to create and apply the LegendItemTemplate.
// create datatemplate, set datatype DataTemplate legendItemTemplate = new DataTemplate(); legendItemTemplate.DataType = typeof(LegendItemTemplate); // root element in datatemplate is border. create and set properties on the border FrameworkElementFactory borderFactory = new FrameworkElementFactory(typeof(Border)); borderFactory.SetValue(Border.BackgroundProperty, new SolidColorBrush(Colors.Red)); // border contains a child TextBlock. create and set properties, then add it as a child of the border FrameworkElementFactory textBlockFactory = new FrameworkElementFactory(typeof(TextBlock)); textBlockFactory.SetBinding(TextBlock.TextProperty, new Binding("Text")); borderFactory.AppendChild(textBlockFactory); // set the border as the visual tree of the DataTemplate legendItemTemplate.VisualTree = borderFactory; // add it to the chart's resources collection this.xamChart1.Resources.Add(new DataTemplateKey(typeof(LegendItemTemplate)), legendItemTemplate); this.xamChart1.Refresh();
Good grief. I never would have figured that one out.
Thanks a lot!