Search code examples
wpfbar-chartdynamic-programminglegenddatavisualization.toolkit

Binding chart LegendItem checkbox to series visibility in WPF in C# codebehind


I have multiple column series chart getting generated in C#. I am further trying to get the legend for this chart with the checkboxes. Such that the chart displays the column series for only legend items that are checked.

I need to do this in C# code behind and not in HTML. I have the below existing code that creates the multiple dynamic column series -

foreach (KeyValuePair<int, string> item in list)
{
  foreach (System.Data.DataRow dRow in dtTable.Rows)
  {
      <formation of listSource>
  }

  ColumnSeries ser = new ColumnSeries { Title = item.Value, IndependentValueBinding = new Binding("Key"), DependentValueBinding = new Binding("Value") };
          ser.ItemsSource = null;
          ser.ItemsSource = listSource;
          ser.DataPointStyle = columnStyleBrown;
          mcChart.Series.Add(ser);
          i++;
      }
}

And I further want to add something to -

ser.LegendItemStyle =

So I need to know how to create a legend style with the check boxes in c#.

There can be 2 ways of achieving this-

  1. Either by modifying the existing legend to contain check boxes also (preferred)
  2. Or to create a new legend altogether

Can anyone please help?

Thanks in advance!


Solution

  • Was able to resolve this -

    xaml code -

    <Grid Name="LayoutRoot">
    <Grid.Resources>
    
        <Style x:Key="CategoryLegendItem" TargetType="DVC:LegendItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="DVC:LegendItem">
                        <StackPanel Orientation="Horizontal">
                            <CheckBox VerticalAlignment="Center" IsChecked="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Owner.Visibility, Mode=TwoWay, Converter={StaticResource BooleanToVisibilityConverter1}}" Margin="0,0,3,0" />
                            <Rectangle Width="8" Height="8" Fill="{Binding Background}" Stroke="{Binding BorderBrush}" StrokeThickness="1" Margin="0,0,3,0" />
                            <DV:Title VerticalAlignment="Center" Content="{TemplateBinding Content}" />
                        </StackPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Grid.Resources>
    <DVC:Chart Name="mcChart"  >
    </DVC:Chart>
    

    Relevant C# code for dynamic column series -

    ColumnSeries ser = new ColumnSeries { Title = kvpNuclide.Value, IndependentValueBinding = new Binding("Key"), DependentValueBinding = new Binding("Value") };
                    ser.ItemsSource = null;
                    ser.ItemsSource = listRelease;
                    ser.DataPointStyle = columnStyleAqua;
                    ser.LegendItemStyle = (Style)LayoutRoot.Resources["CategoryLegendItem"];
                    mcChart.Series.Add(ser);