[英]How do I reference a rectangle created programmatically, with XAML?
I am working with WPF for the first time. 我是第一次与WPF合作。 I am creating a rectangle object & adding it as a child of a canvas.
我正在创建一个矩形对象,并将其添加为画布的子代。
How do I reference it in XAML? 如何在XAML中引用它?
I want to be able to rotate it over time but don't know how to access it from the MainWindow.xaml code... 我希望能够随时间旋转它,但是不知道如何从MainWindow.xaml代码访问它...
I haven't been able to find an answer to this anywhere (maybe you can't do it this way?) 我一直无法在任何地方找到答案(也许您不能这样吗?)
Edit: 编辑:
I tried setting the Name
property of the rectangle to Test
(in C# code) and then doing 我尝试将矩形的
Name
属性设置为Test
(在C#代码中),然后执行
<Rectangle x:Name="Test">
<Rectangle.LayoutTransform>
<RotateTransform Angle="-45"/>
</Rectangle.LayoutTransform>
</Rectangle>
(This didn't work) (这没有用)
If you create a control in C#, you cannot access it in XAML. 如果在C#中创建控件,则无法在XAML中访问它。 I think you must create the necessary animation in C# too.
我认为您也必须在C#中创建必要的动画。
Applying your rotation in C# could look like this: 在C#中应用轮换可能看起来像这样:
var rect = new Rectangle();
rect.LayoutTransform = new RotateTransform() { Angle = -45 };
parentPanel.Children.Add(rect);
The better way would be to generate the Rectangle
in XAML and apply there the animation. 更好的方法是在XAML中生成
Rectangle
并在其中应用动画。 But this depends on your exact situation. 但这取决于您的实际情况。 eg you can create a single
Rectangle
in XAML and use this one or you can bind an ItemsControl
and create a Rectangle
in the ItemTemplate
for each entry in the binded list. 例如,您可以在XAML中创建一个
Rectangle
并使用它,也可以绑定ItemsControl
并在ItemTemplate
为绑定列表中的每个条目创建Rectangle
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.