在后面的代码中更改Canvas.Left属性吗?

问题描述 投票:96回答:3

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

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

c# wpf code-behind attached-properties
3个回答
162
投票
Canvas.SetLeft(theObject, 50)


50
投票

尝试一下

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

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

  • SetValue
  • GetValue
  • ClearValue

Edit将集合更新为使用双精度字面量,因为目标类型是双精度数。


12
投票

当我们更改“对象”的属性时,最好使用JaredPar建议的方法:

theObject.SetValue(Canvas.LeftProperty, 50d);
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.