Measurement Studio for .NET Languages

Showing results for 
Search instead for 
Did you mean: 

How do I add Items to a Legend in WPF

Go to solution

I have added a Grpah with three plots. Added a Legend and wanted to have 3 plots of the graph as the Items to my Legend. Is there any way I can add the Legend items at design time?




<ni.Plot x:name="x1"/>

<ni.Plot x:name="x2"/>

<ni.Plot x:name="x3"/>



<ni:Legend items{???} />


Seems Items is read only collection....

0 Kudos
Message 1 of 6
Accepted by topic author BabaGoud

You can use the ItemsSource property to populate the Legend. You can show all items by using the graph itself, or you can limit it to a specific collection, as in this XAML from the Standard\DefaultPlotRenderers example installed with Measurement Studio:


<ni:Legend ItemsSource="{Binding AllPlots, ElementName=graph}"
           ItemBackground="{Binding Background, ElementName=graph}"
           BorderBrush="{Binding BorderBrush, ElementName=graph}"
           IsTabStop="False" />
~ Paul H
0 Kudos
Message 2 of 6

Hi Paul,


I have 2 graphs on the window. the first graph has only one plot and the second graph has 3 plots.

My Legend needs to contain one item as a source from the first graph and only 2 of the plots as two more items from the second graph. Is there a way to mention plots from 2 different graphs as Itemsource of the Legend?

0 Kudos
Message 3 of 6

Because of the amount of filtering involved, I think the simplest approach would be to initialize a collection in code-behind to contain the specific plots you were interested in. (If you had wanted to combine all items from multiple collections, then a WPF CompositeCollection could work as a purely declarative solution.)


The Legend will try to display the items from any collection you provide to ItemsSource, so based on your description:


<ni:Graph x:Name="graph1">
        <ni:Plot Label="Graph 1, Plot 1" />

<ni:Graph x:Name="graph2">
        <ni:Plot Label="Graph 2, Plot 1" />
        <ni:Plot Label="Graph 2, Plot 2" />
        <ni:Plot Label="Graph 2, Plot 3" />

<ni:Legend x:Name="legend" />

var plots = new List<Plot>( );
plots.Add( graph1.Plots[0] );
plots.AddRange( graph2.Plots.Take( 2 ) );
legend.ItemsSource = plots;
~ Paul H
Message 4 of 6

Hi Paul,


I have an application where I have to plot data based on user selection and show them in a legend. So I have to create plots dynamically and add plot labels from a ViewModel


Then I have binded Legend to these plots and got the labels displayed on legend.




 The problem is - clicking on the legend items no longer change the visibility of the plots. 


 Can you please help?





0 Kudos
Message 5 of 6

[I see you posted a new question, so I have moved my answer there]

~ Paul H
0 Kudos
Message 6 of 6