自定义ComboBox,ComboItem

时间:2012-12-07 19:50:14

标签: c# wpf combobox

我需要创建一个显示形状的自定义组合框。我通过扩展Shape类并实现DefiningGeometry函数来创建形状,如下所示:

public abstract class MyShape : Shape
{


    public static readonly DependencyProperty SizeProperty = DependencyProperty.Register("Size", typeof(Double), typeof(MapShape));
    public static readonly DependencyProperty RotationAngleProperty = DependencyProperty.Register("RotationAngle", typeof(Double), typeof(MapShape), new PropertyMetadata(0.0d));

    public double Size
    {
        get { return (double)this.GetValue(SizeProperty); }
        set { this.SetValue(SizeProperty, value); }
    }

    public double RotationAngle
    {
        get { return (double)this.GetValue(RotationAngleProperty); }
        set { this.SetValue(RotationAngleProperty, value); }
    }

    protected override Geometry DefiningGeometry
    {
        get
        { return null; }
    }
}

我可以扩展该类并创建我想要的任何其他形状。例如,我有一个看起来像箭头的那个:

public class Arrow : MyShape
{
    public Arrow() { 
    }

    protected override Geometry DefiningGeometry
    {
        get
        {
            double oneThird = this.Size / 3;
            double twoThirds = (this.Size * 2) / 3;
            double oneHalf = this.Size / 2;

            Point p1 = new Point(0.0d, oneThird);
            Point p2 = new Point(0.0d, twoThirds);
            Point p3 = new Point(oneHalf, twoThirds);
            Point p4 = new Point(oneHalf, this.Size);

            Point p5 = new Point(this.Size, oneHalf);
            Point p6 = new Point(oneHalf, 0);
            Point p7 = new Point(oneHalf, oneThird);


            List<PathSegment> segments = new List<PathSegment>(3);
            segments.Add(new LineSegment(p1, true));
            segments.Add(new LineSegment(p2, true));
            segments.Add(new LineSegment(p3, true));
            segments.Add(new LineSegment(p4, true));

            segments.Add(new LineSegment(p5, true));
            segments.Add(new LineSegment(p6, true));
            segments.Add(new LineSegment(p7, true));

            List<PathFigure> figures = new List<PathFigure>(1);
            PathFigure pf = new PathFigure(p1, segments, true);
            figures.Add(pf);
            RotateTransform rt = new RotateTransform(this.RotationAngle);

            Geometry g = new PathGeometry(figures, FillRule.EvenOdd, rt);

            return g;
        }
    }
}

我可以在XAML或代码上添加这些形状,它们工作得很好。

现在,这些形状显示在我表单中的某个图形对象上,这是无关紧要的。我的要求是客户端从ComboBox更改表单中图形对象上的形状。所以,基本上我也需要在组合框中显示形状。我真的不需要使用我在这里展示的这些类,只是为了澄清我将它们添加到本说明中。但我确实需要自定义组合框以显示项目中的形状。我认为的一种方法是使用ControlTemplate,任何其他想法,代码,读数? 谢谢!

1 个答案:

答案 0 :(得分:1)

如果我理解,可以通过自定义ItemTemplate的{​​{1}}属性来实现您的目标。

ComboBox