0

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);
dllhell
  • 1,987
  • 3
  • 34
  • 51
Corio
  • 395
  • 7
  • 20
  • 1
    Have you tried your code? – Hamlet Hakobyan Sep 21 '13 at 17:35
  • C:\Users\neizv_000\Documents\Visual Studio 2012\Projects\Lab 6.5\Lab 6.5\MainWindow.xaml.cs(57,17,57,50): error CS1502: The best overloaded method match for 'System.Windows.DependencyObject.SetValue(System.Windows.DependencyProperty, object)' has some invalid arguments 1>C:\Users\neizv_000\Documents\Visual Studio 2012\Projects\Lab 6.5\Lab 6.5\MainWindow.xaml.cs(57,39,57,45): error CS1503: Argument 1: cannot convert from 'double' to 'System.Windows.DependencyProperty' – Corio Sep 21 '13 at 17:49
  • Try `childByIndex.SetValue(HeightProperty, 15);` – Hamlet Hakobyan Sep 21 '13 at 19:05

2 Answers2

2

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);
Nitin
  • 18,344
  • 2
  • 36
  • 53
  • Yes, I have a Rectangle, but your code gives me an error: 1>C:\Users\neizv_000\Documents\Visual Studio 2012\Projects\Lab 6.5\Lab 6.5\MainWindow.xaml.cs(57,72,57,86): error CS1061: 'bool' does not contain a definition for 'HeightProperty' and no extension method 'HeightProperty' accepting a first argument of type 'bool' could be found (are you missing a using directive or an assembly reference?) – Corio Sep 21 '13 at 18:03
  • it should work.. can you check if ((Rectangle)canvas.Children[index]) is actually returning a rectangle? – Nitin Sep 21 '13 at 18:10
  • Something strange, in one project it works, and in another is not. The error message above is from not-working one, I`l try to figure it out on my own. But if you have some ideas, don`t be shy. Thanks for help, I was torturing with it for entire day. – Corio Sep 21 '13 at 19:42
1

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);
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
  • Your way works too, thanks. But I have not enough reputation to rate your answers, sorry. You helped a lot. – Corio Sep 21 '13 at 19:44