Search code examples
c#wpfwpftoolkit

(WPF Toolkit) Setting the color for each DataPoint in Column Series


I have a WPF Toolkit Chart with a ColumnSeries. The ColumnSeries has a SelectionChanged Event in the code behind and a default style that affects all the columns in the series

<chartingToolkit:ColumnSeries DependentValuePath="Value" IndependentValuePath="Key" ItemsSource="{Binding ColumnValues}" IsSelectionEnabled="True" SelectionChanged="ColumnSeries_SelectionChanged">
    <chartingToolkit:ColumnSeries.DataPointStyle>
        <Style TargetType="chartingToolkit:ColumnDataPoint">
            <Setter Property="Background" Value="{StaticResource HeaderForegroundBrush}" />
        </Style>
    </chartingToolkit:ColumnSeries.DataPointStyle>
</chartingToolkit:ColumnSeries>

I can change the style of the entire columnseries in the codebehind, but how can the style of a single column be changed? Is this possible at all?

private void ColumnSeries_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Style lineStyle = new Style { TargetType = typeof(ColumnDataPoint) };
    lineStyle.Setters.Add(new Setter(ColumnDataPoint.BackgroundProperty, (Brush)Application.Current.Resources["Line1Brush"]));
    ((ColumnSeries)sender).DataPointStyle = lineStyle;
}

Solution

  • You could use a helper method to find the ColumnDataPoint elements in the visual tree and then set any property you want of an individual element, e.g.:

    private void ColumnSeries_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ColumnSeries cs = sender as ColumnSeries;
        IEnumerable<ColumnDataPoint> columns = FindVisualChildren<ColumnDataPoint>(cs);
        foreach (var column in columns)
        {
            if (column.DataContext == e.AddedItems[0]) //change the background of the selected one
            {
                column.Background = Brushes.DarkBlue;
                break;
            }
        }
    
    }
    
    private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
    {
        if (depObj != null)
        {
            int NbChild = VisualTreeHelper.GetChildrenCount(depObj);
    
            for (int i = 0; i < NbChild; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
    
                if (child != null && child is T)
                {
                    yield return (T)child;
                }
    
                foreach (T childNiv2 in FindVisualChildren<T>(child))
                {
                    yield return childNiv2;
                }
            }
        }
    }