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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/541420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:25:52  来源:igfitidea点击:

Change Canvas.Left property in code behind?

c#wpfcode-behindattached-properties

提问by Edward Tanguay

I have a rectangle in my XAML and want to change its Canvas.Leftproperty in code behind:

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

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?

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

采纳答案by AnthonyWJones

Canvas.SetLeft(theObject, 50)

回答by JaredPar

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

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

  • SetValue
  • GetValue
  • ClearValue
  • 设定值
  • 获取值
  • 清除值

EditUpdated the set to use a double literal since the target type is a double.

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

回答by Budda

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

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

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