(WPF Toolkit)为Column Series中的每个DataPoint设置颜色

时间:2017-09-11 12:34:03

标签: c# wpf wpftoolkit

我有一个带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>

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

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

1 个答案:

答案 0 :(得分:1)

您可以使用辅助方法在可视化树中查找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;
            }
        }
    }
}