1

这段代码有什么问题。我完全一无所知。

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

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

4

1 回答 1

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;

Is meaningless in this context. Either set a fixed size or change your control to inherit Grid instead of StackPanel.

于 2012-12-19T09:23:42.323 回答