简体   繁体   中英

How to change a value of UIElement

I have a WPF application and Canvas in there. In Canvas I have a Rectangle. How can I change his properties, like Height or Width while program is already processing? Something like:

int index = 0; 
var childByIndex = canvas.Children[index]; 
childByIndex.SetValue(Height, 15);

你必须告诉你想要设置哪种类型的dp,如下所示:

((Rectangle)canvas.Children[index]).SetValue(Rectangle.HeightProperty, 15.0);

The easiest way would be to give your rectangle a name in XAML and then use it in your code:

<Canvas>
    <Rectangle x:Name="rect" />
</Canvas>
rect.Height = 15;

If for some reason you can't give your rectangle a name in XAML, you can cast your found object to Rectangle before doing the operation:

Rectangle rect = (Rectangle)childByIndex;
rect.Height = 15;

If you're looking to change an attached property, like the location in the canvas, you can do it like this:

Canvas.SetTop(rect, 10);
Canvas.SetLeft(rect, 20);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM