问题描述
我在 WPF 应用程序中使用 WPF Toolkit Chart 和 PieChart.
I am using WPF Toolkit Chart with PieChart in my WPF Application.
我想将饼图图片中的默认白色背景更改为透明..
I want to change by default white background to Transparent in PieChart Picture..
如何赋予风格以实现这一目标
How to give Style to Achieve that
推荐答案
如果您查看可视化树,您会发现必须更改网格和边框的背景属性才能将背景更改为透明(下图中以黄色突出显示的元素).
If you looked at visual tree you find out that you must change Background property of grid and border to change background to transparent (elements highlighted in yellow in the below picture).
为此,您可以在 Loaded
事件中更改颜色.首先,您必须找到名称为 ChartArea
的 EdgePanel
,然后您必须更改网格和边框的颜色.如果您还想将 Legend
的背景设置为透明,您必须找到 Legend
元素并设置适当的属性.
To do that you can change color in Loaded
event. First you must find EdgePanel
with name ChartArea
and after that you must change color of grid and border. If you want to set also background of Legend
to transparent you must find Legend
element and set appropriate properties.
<DVC:Chart Canvas.Top="80" Canvas.Left="10" Name="mcChart"
Width="400" Height="250"
Background="Orange"
Loaded="mcChart_Loaded">
<DVC:Chart.Series>
<DVC:PieSeries Title="Experience"
ItemsSource="{StaticResource FruitCollection}"
IndependentValueBinding="{Binding Path=Name}"
DependentValueBinding="{Binding Path=Share}">
</DVC:PieSeries>
</DVC:Chart.Series>
</DVC:Chart>
代码隐藏:
private void mcChart_Loaded(object sender, RoutedEventArgs e)
{
EdgePanel ep = VisualHelper.FindChild<EdgePanel>(sender as Chart, "ChartArea");
if (ep != null)
{
var grid = ep.Children.OfType<Grid>().FirstOrDefault();
if (grid != null)
{
grid.Background = new SolidColorBrush(Colors.Transparent);
}
var border = ep.Children.OfType<Border>().FirstOrDefault();
if (border != null)
{
border.BorderBrush = new SolidColorBrush(Colors.Transparent);
}
}
Legend legend = VisualHelper.FindChild<Legend>(sender as Chart, "Legend");
if (legend != null)
{
legend.Background = new SolidColorBrush(Colors.Transparent);
legend.BorderBrush = new SolidColorBrush(Colors.Transparent);
}
}
Helper 类在这种情况下查找子元素 EdgePanel
:
Helper class to find child element in this case EdgePanel
:
class VisualHelper
{
public static T FindChild<T>(DependencyObject parent, string childName) where T : DependencyObject
{
if (parent == null) return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
T childType = child as T;
if (childType == null)
{
foundChild = FindChild<T>(child, childName);
if (foundChild != null) break;
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
if (frameworkElement != null && frameworkElement.Name == childName)
{
foundChild = (T)child;
break;
}
}
else
{
foundChild = (T)child;
break;
}
}
return foundChild;
}
}
这篇关于如何为 WPF 工具包图表赋予样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!