101

我的 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;
}

有谁知道这样做的语法是什么?

4

3 回答 3

170
Canvas.SetLeft(theObject, 50)

于 2009-02-12T14:24:05.983 回答
56

试试这个

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

DependencyObject(大多数 WPF 类的基础)上有一组方法,它们允许对所有依赖项属性进行公共访问。他们是

  • 设定值
  • 获取值
  • 清除值

编辑更新了集合以使用双字面值,因为目标类型是双精度值。

于 2009-02-12T14:22:31.697 回答
12

由于我们正在更改“对象”的属性,因此最好使用 JaredPar 建议的方法:

theObject.SetValue(Canvas.LeftProperty, 50d);
于 2010-08-16T23:23:10.820 回答