我有一个UserControl
,在XAML中引用方式如下:
<local:ColumnGraphRenderCtrl x:Name="graphCtrl" Grid.Column="1"
Height="Auto" Width="Auto"/>
这个UserControl
有几个矩形形状,它们正常显示。
但是,如果我指定一个Background
颜色,指定的颜色会遮挡矩形,只会显示颜色。例如:
<local:ColumnGraphRenderCtrl x:Name="graphCtrl" Background="Blue" Grid.Column="1"
Height="Auto" Width="Auto"/>
如果我将颜色更改为“透明”,那么矩形确实变得可见。
我还尝试为UserControl
(作为Style
的一部分)使用ControlTemplate
,但结果相同(即背景色阻挡了UserControl的内容)。
我查看了MSDN上的Control.Background属性,该属性提供以下说明:
Background属性仅适用于控件的静止状态。控件的默认样式指定其状态更改时的外观。例如,如果您在按钮上设置Background属性,则仅当按钮未被按下或禁用时才具有该值。如果要创建具有更高级别的背景自定义的控件,则必须定义控件的样式。
此属性仅影响使用Background属性作为参数的模板的控件。对于其他控件,此属性没有影响。
MSDN中的备注有什么意义,我如何指定背景颜色而不阻止控件内容?
编辑:如果手动在代码后台添加内容控件(矩形),是否会有所不同。
UserControl代码:
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++;
}
}
}
}
}
UserControl
代码吗?我按照你的描述尝试自己创建了一个,但是无法复现问题。 - Tzah Mamathis.Background = Brushes.Blue;
。 - Sabuncu