以编程方式将路径数据分配给 Thumb 控件并将其添加到 Canvas

Assign Path data to Thumb control programmatically and add it to Canvas

我想做的是在特定位置以编程方式创建一个矩形,我想在添加到 Canvas 之前将其分配给 Thumb 控件。原因是我想稍后实现拖放。但是下面这段代码的问题是我从来没有在 Canvas 中看到任何东西,请帮忙。当我尝试调试时,我在事实变量中看不到任何数据,并且 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);
        }

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

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

下面是代码的两个版本。 1 使用 XamlReader.Parse 和 2 使用 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);

希望对您有所帮助。