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

时间:2023-03-10 00:38:54
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()方法 //Right\Buttom\Left同

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);