(WPF 工具包)为列系列中的每个数据点设置颜色

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

我有一个带有 ColumnSeries 的 WPF 工具包图表。 ColumnSeries 在代码隐藏中有一个 SelectionChanged 事件和影响系列中所有列的默认样式

<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>

我可以在代码隐藏中更改整个columnseries的样式,但是如何更改单个列的样式?这可能吗?

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;
}

您可以使用辅助方法在可视化树中找到 ColumnDataPoint 元素,然后设置任何 属性 您想要的单个元素,例如:

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;
            }
        }
    }
}