How to I access an attached property in code behind?

 ̄綄美尐妖づ 提交于 2019-11-27 00:32:42

问题


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

<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?


回答1:


Canvas.SetLeft(theObject, 50)




回答2:


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

  • SetValue
  • GetValue
  • ClearValue

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




回答3:


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

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


来源:https://stackoverflow.com/questions/541420/how-to-i-access-an-attached-property-in-code-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!