更改 Canvas。在代码后面留下属性?

我有一个矩形在我的 XAML,并希望改变其 Canvas.Left后面的代码属性:

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

但这不管用:

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

有人知道这样做的语法吗?

54255 次浏览

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.

Canvas.SetLeft(theObject, 50)

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

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