首页 > 解决方案 > 以编程方式将路径数据分配给 Thumb 控件并将其添加到 Canvas

问题描述

我想做的是在特定位置以编程方式创建一个矩形,我想在添加到 Canvas 之前将其分配给 Thumb 控件。原因是我想稍后实现拖放。但是下面这段代码的问题是我从来没有在画布内看到任何东西,请帮忙。当我尝试调试时,我在 fact 变量中看不到任何数据,并且 t.HasContent 为假。

 public void DrawShape2()
        {
            Thumb th = new Thumb();

            Path myPath1 = new Path();
            myPath1.Stroke = Brushes.Black;
            myPath1.StrokeThickness = 1;
            SolidColorBrush mySolidColorBrush = new SolidColorBrush();
            mySolidColorBrush.Color = Color.FromArgb(255, 204, 204, 255);
            myPath1.Fill = mySolidColorBrush;

            Point a = new Point(25, 150);
            Point b = new Point(500, 490);

            Rect myRect1 = new Rect(a, b);
            RectangleGeometry myRectangleGeometry1 = new RectangleGeometry();
            myRectangleGeometry1.Rect = myRect1;

            GeometryGroup myGeometryGroup1 = new GeometryGroup();
            myGeometryGroup1.Children.Add(myRectangleGeometry1);

            myPath1.Data = myGeometryGroup1;

            ControlTemplate t = new ControlTemplate();
            var fact = new FrameworkElementFactory(typeof(Path));
            fact.SetValue(Path.DataProperty, myPath1.Data);
            t.VisualTree = fact;
            th.Template = t;
            cnv.Children.Add(th);
        }

标签: c#wpfcontroltemplateframeworkelementfactory

解决方案


您的代码无法正常工作的原因是您没有ControlTemplate正确创建代码。

注意:Microsoft 建议您将 XAML 创建为字符串,然后使用XamlReader.Parse而不是使用FrameworkElementFactory.

下面是两个版本的代码。1 使用XamlReader.Parse2 使用FrameworkElementFactory.

XamlReader.Parse

var th = new Thumb();

var controlTemplate =
    "<ControlTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" TargetType=\"Thumb\">" +
    "<Path Stroke=\"Black\" StrokeThickness=\"1\" Fill=\"#FFCCCCFF\">" +
    "<Path.Data>" +
    "<GeometryGroup>" +
    "<RectangleGeometry Rect=\"25,150,500,490\"/>" +
    "</GeometryGroup>" +
    "</Path.Data>" +
    "</Path>" +
    "</ControlTemplate>";

th.Template = (ControlTemplate) XamlReader.Parse(controlTemplate);

Canvas.Children.Add(th);

框架元素工厂

var th = new Thumb();

var a = new Point(25, 150);
var b = new Point(500, 490);

var myRect1 = new Rect(a, b);
var myRectangleGeometry1 = new RectangleGeometry {Rect = myRect1};

var myGeometryGroup1 = new GeometryGroup();
myGeometryGroup1.Children.Add(myRectangleGeometry1);

var t = new ControlTemplate(typeof(Thumb));
var path = new FrameworkElementFactory(typeof(Path));
path.SetValue(Shape.StrokeProperty, Brushes.Black);
path.SetValue(Shape.StrokeThicknessProperty, 1d);
path.SetValue(Shape.FillProperty, new SolidColorBrush{Color = Color.FromArgb(255, 204, 204, 255)});
path.SetValue(Path.DataProperty, myGeometryGroup1);
t.VisualTree = path;
th.Template = t;
Canvas.Children.Add(th);

我希望这是有帮助的。


推荐阅读