C# Wpf 后台代码设定UIElement的Canvas位置属性值

后台in-code设定元件UIElement的Canvas位置属性的两种方法:

1.UIElement.SetValue()方法

uiElement.SetValue(Canvas.TopProperty, 100.0);
uiElement.SetValue(Canvas.LeftProperty, 100.0);

2. Canvas.SetTop()方法 //RightButtomLeft同

Canvas.SetTop(uiElement, 100.0);
Canvas.SetLeft(uiElement, 100.0);

值得注意的是:

  如果需要来回反复设定UIElement的位置属性,且定位点变化(左上、左下、右上、右下),需要将另两个属性置为NaN,否则意想不到的结果。

//
uiElement.SetValue(Canvas.TopProperty, 100.0);
uiElement.SetValue(Canvas.LeftProperty, 100.0);
uiElement.SetValue(Canvas.RightProperty, Double.NaN);
uiElement.SetValue(Canvas.ButtomProperty, Double.NaN);

//
uiElement.SetValue(Canvas.TopProperty,  Double.NaN);
uiElement.SetValue(Canvas.LeftProperty,  Double.NaN);
uiElement.SetValue(Canvas.RightProperty, 100.0);
uiElement.SetValue(Canvas.ButtomProperty, 100.0);
原文地址:https://www.cnblogs.com/gradual/p/7815911.html