Change Canvas.Left property in code behind?
Asked Answered
K

3

103

I have a rectangle in my XAML and want to change its Canvas.Left property in code behind:

<UserControl x:Class="Second90.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300" KeyDown="txt_KeyDown">
    <Canvas>
        <Rectangle 
            Name="theObject" 
            Canvas.Top="20" 
            Canvas.Left="20" 
            Width="10" 
            Height="10" 
            Fill="Gray"/>
    </Canvas>
</UserControl>

But this doesn't work:

private void txt_KeyDown(object sender, KeyEventArgs e)
{
    theObject.Canvas.Left = 50;
}

Does anyone know what the syntax is to do this?

Krell answered 12/2, 2009 at 14:18 Comment(0)
D
172
Canvas.SetLeft(theObject, 50)

Distasteful answered 12/2, 2009 at 14:24 Comment(3)
+1, gotta love type safety. I am curious though why SetLeft takes a UIElement instead of a DependencyObjectDupondius
@JaredPar: at a guess I would say that since SetLeft is specifically a method of Canvas it understands what types it would make sense give a Left property to. It deems this to be UIElement, this perhaps increases the detection of faulty code where accidentally the wrong variable is passed to it.Distasteful
msdn.microsoft.com/en-us/library/… Canvas.Left is an attached property, which supports a XAML usage. When setting this property in code, use SetLeft instead.Otalgia
D
57

Try this

theObject.SetValue(Canvas.LeftProperty, 50d);

There is a group of methods on DependencyObject (base of most WPF classes) which allow the common access to all dependency properties. They are

  • SetValue
  • GetValue
  • ClearValue

Edit Updated the set to use a double literal since the target type is a double.

Dupondius answered 12/2, 2009 at 14:22 Comment(2)
Thanks, to get this to work I had to cast the integer: theObject.SetValue(Canvas.LeftProperty, (double)50);Krell
No, for this specify numeric constant in double format: heObject.SetValue(Canvas.LeftProperty, 50.0);Parament
P
12

As we are changing the property of the 'object', it would be better to use method suggedte by JaredPar:

theObject.SetValue(Canvas.LeftProperty, 50d);
Parament answered 16/8, 2010 at 23:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.