这段代码出了什么问题。我完全无能为力。
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Windows.Data;
namespace CustomControls
{
public class PercentFiller: StackPanel
{
public Rectangle _FillerRectangle = null;
public PercentFiller()
{
_FillerRectangle = new Rectangle();
_FillerRectangle.Height = this.Height;
_FillerRectangle.Width = 20;
_FillerRectangle.SetBinding(Rectangle.FillProperty, new Binding() {
Source = this,
Path = new PropertyPath("FillColorProperty"),
Mode = BindingMode.TwoWay
});
this.Background = new SolidColorBrush(Colors.LightGray);
this.Children.Add(_FillerRectangle);
this.UpdateLayout();
}
public static readonly DependencyProperty FillColorProperty = DependencyProperty.Register(
"FillColor",
typeof(Brush),
typeof(Compressor),
new PropertyMetadata(new SolidColorBrush(Color.FromArgb(255, 134, 134, 134))));
[Description("Gets or sets the fill color")]
public Brush FillColor
{
get { return (Brush) GetValue(FillColorProperty); }
set { SetValue (FillColorProperty, value); }
}
}
}
当我将此控件添加到另一个项目时,不会显示矩形控件。请有人帮我解决这个问题。
答案 0 :(得分:1)
您的绑定错误(您的_FillerRectangle
没有DataContext
)。
此外,您可以将依赖项属性本身传递给PropertyPath
。
尝试更改您的绑定:
_FillerRectangle.DataContext = this; //#1: add this line
_FillerRectangle.SetBinding(Rectangle.FillProperty, new Binding()
{
Path = new PropertyPath(FillColorProperty), // #2: no longer a string
Mode = BindingMode.TwoWay
});
DataContext
“告诉”你绑定的依赖属性所在的绑定。
此外,您的DependencyProperty
声明中存在错误:
public static readonly DependencyProperty FillColorProperty = DependencyProperty.Register(
"FillColor",
typeof(Brush),
typeof(Compressor), // <- ERROR ! should be typeof(PercentFiller)
new PropertyMetadata(new SolidColorBrush(Color.FromArgb(255, 134, 134, 134))));
标记的行应该是属性的包含对象的类型,因此在这种情况下,它应该是typeof(PercentFiller)
。
更新:
我忘记添加:StackPanel
本身没有尺寸,所以:
_FillerRectangle.Height = this.Height;
在这种背景下毫无意义。设置固定大小或更改您的控件以继承Grid
而不是StackPanel
。