How to change a value of UIElement

喜夏-厌秋 提交于 2019-12-12 02:53:27

问题


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);

回答1:


You will have to tell which dp of which type you want to set like below:

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



回答2:


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);


来源:https://stackoverflow.com/questions/18935482/how-to-change-a-value-of-uielement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!