Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Canvas.Left property in code behind?

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?

like image 945
Edward Tanguay Avatar asked Feb 12 '09 14:02

Edward Tanguay


3 Answers

Canvas.SetLeft(theObject, 50)

like image 82
AnthonyWJones Avatar answered Nov 17 '22 09:11

AnthonyWJones


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.

like image 25
JaredPar Avatar answered Nov 17 '22 09:11

JaredPar


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

theObject.SetValue(Canvas.LeftProperty, 50d);
like image 12
Budda Avatar answered Nov 17 '22 09:11

Budda