【问题标题】:Change Canvas.Left property in code behind?在后面的代码中更改 Canvas.Left 属性?
【发布时间】:2010-10-07 04:27:30
【问题描述】:

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


    【解决方案1】:
    Canvas.SetLeft(theObject, 50)
    

    【讨论】:

    • +1,必须喜欢类型安全。我很好奇为什么 SetLeft 采用 UIElement 而不是 DependencyObject
    • @JaredPar:我猜我会说,因为 SetLeft 是 Canvas 的一种特殊方法,它理解将 Left 属性赋予哪些类型是有意义的。它认为这是 UIElement,这可能会增加对错误代码的检测,因为错误的变量会意外传递给它。
    • msdn.microsoft.com/en-us/library/…Canvas.Left 是一个附加属性,它支持 XAML 用法。在代码中设置此属性时,请改用 SetLeft。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      试试这个

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

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

      • 设置值
      • 获取值
      • 清除值

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

      【讨论】:

      • 谢谢,为了让它工作,我必须转换整数:theObject.SetValue(Canvas.LeftProperty, (double)50);
      • 否,为此指定双精度格式的数字常量:heObject.SetValue(Canvas.LeftProperty, 50.0);
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多