如何在代码后面访问附加属性?

Edw*_*uay 94 c# wpf code-behind attached-properties

我的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>
Run Code Online (Sandbox Code Playgroud)

但这不起作用:

private void txt_KeyDown(object sender, KeyEventArgs e)
{
    theObject.Canvas.Left = 50;
}
Run Code Online (Sandbox Code Playgroud)

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

Ant*_*nes 156

Canvas.SetLeft(theObject, 50)
Run Code Online (Sandbox Code Playgroud)

  • @JaredPar:猜测我会说,因为SetLeft特别是Canvas的一个方法,所以它理解了什么类型,它给出了一个Left属性.它认为这是UIElement,这可能会增加错误代码的检测,意外地将错误的变量传递给它. (4认同)

Jar*_*Par 50

试试这个

theObject.SetValue(Canvas.LeftProperty, 50d);
Run Code Online (Sandbox Code Playgroud)

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

  • 设定值
  • 的GetValue
  • ClearValue

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


Bud*_*dda 12

当我们改变'对象'的属性时,最好使用JaredPar的方法suggedte:

theObject.SetValue(Canvas.LeftProperty, 50d);
Run Code Online (Sandbox Code Playgroud)