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;

この文脈では無意味です。固定サイズを設定するかGridコントロールをの代わりに継承するように変更してくださいStackPanel

于 2012-12-19T09:23:42.323 に答える