c# - 以编程方式将路径数据分配给 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);
}
解决方案
您的代码无法正常工作的原因是您没有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);
我希望这是有帮助的。
推荐阅读
- node.js - 是否可以直接从 Influxdb 获取数据并将其呈现在 Angular Dashboard 上?
- html - 输入类型日期的 VoiceOver 错误
- c# - 如何在 Visual Studio 2017 的构建后事件中设置 dll 文件的路径
- python - 仅删除许多重复对象之一
- django - 如何在 django 中更改用户 ID?
- c++ - Makefile如何指定包含目录
- c# - 在同一程序集中混合 C++/C 和 C# 的 MSVS 解决方案
- javascript - 有没有比这种方法更好的方法来实现“输入按键,登录”?
- php - 如何在变量中实例化具有类名的对象?
- c# - 从 DataGridViewRowCollection c# 添加行