我有一个UserControl
,在 XAML 中引用如下:
<local:ColumnGraphRenderCtrl x:Name="graphCtrl" Grid.Column="1"
Height="Auto" Width="Auto"/>
The UserControl
有问题的有几个矩形形状,它们显示得很好。
However,如果我指定一个Background
color,指定的颜色会遮挡矩形,只显示颜色。例如:
<local:ColumnGraphRenderCtrl x:Name="graphCtrl" Background="Blue" Grid.Column="1"
Height="Auto" Width="Auto"/>
(如果我将颜色更改为“透明”,矩形就会变得可见。)
我也尝试使用ControlTemplate
为了UserControl
(作为Style
),但我得到了相同的结果(即背景颜色阻挡了 UserControl 的内容)。
我查了一下控制.背景属性于MSDN http://msdn.microsoft.com/en-us/library/system.windows.controls.control.background%28v=vs.110%29.aspx其中提供了以下备注:
背景属性仅适用于静止状态
控制。控件的默认样式指定其外观
当控件的状态改变时。例如,如果您设置
按钮上的背景属性,按钮仅在以下情况下才具有该值:
它没有被按下或禁用。如果你想创建一个控件
有更高级的背景定制,必须定义
控件的样式。
该属性仅影响其模板使用
背景属性作为参数。在其他控件上,此属性
没有影响。
MSDN中的注释有何意义,如何指定背景颜色而不遮挡控件内容?
编辑:如果有影响的话,内容控件(矩形)是在代码隐藏中手动添加的。
用户控制代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
namespace GraphingWithShapes
{
public partial class ColumnGraphRenderCtrl: UserControl
{
private ObservableCollection<NameValuePair> _dataPoints = null;
private List<Color> _columnColors = new List<Color>() { Colors.Blue, Colors.Red, Colors.Green };
public ColumnGraphRenderCtrl()
{
InitializeComponent();
}
public void SetData(ObservableCollection<NameValuePair> data)
{
_dataPoints = data;
_dataPoints.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_dataPoints_CollectionChanged);
InvalidateVisual();
}
void _dataPoints_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
InvalidateVisual();
}
public double GetLargestValue()
{
double value = 0;
foreach (NameValuePair nvp in _dataPoints)
{
value = Math.Max(value, nvp.Value);
}
return value;
}
protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
{
base.OnMouseDoubleClick(e);
}
protected override void OnRender(DrawingContext drawingContext)
{
if (_dataPoints != null)
{
double spaceToUseY = ActualHeight * 0.8;
double spaceToUseX = ActualWidth * 0.8;
double barWidth = spaceToUseX / _dataPoints.Count;
double largestValue = GetLargestValue();
double unitHeight = spaceToUseY / largestValue;
double bottom = ActualHeight * 0.9;
double left = ActualWidth * 0.1;
Brush fillBrush;
Pen outlinePen = new Pen(Brushes.Black, 1);
int nIndex = 0;
Rect rect;
double height;
foreach (NameValuePair nvp in _dataPoints)
{
fillBrush = new SolidColorBrush(_columnColors[nIndex % _columnColors.Count]);
height = (nvp.Value * unitHeight);
rect = new Rect(left, bottom - height, barWidth, height);
drawingContext.DrawRectangle(fillBrush, outlinePen, rect);
left += rect.Width;
nIndex++;
}
}
}
}
}