Silverlight 5 自定义控件无法正常工作



这段代码有什么问题。我完全没有头绪。

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

当我将此控件添加到另一个项目时,矩形控件未显示。请有人帮我解决这个问题。

你绑定错误(你的_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

最新更新