我有一个垂直StackPanel,我希望它包含Line-child,其.X2值绑定到parent-StackPanel的ActualWidth。类似的东西:
StackPanel sp = new StackPanel();
sp.Orientation = Orientation.Vertical;
(...)
Line line = new Line();
line.X1 = 0;
line.X2 = <Some binding to sp.ActualWidth>;
// line.Y1 = line.Y2 - will it set it's value to 0 by default?
line.StrokeThickness = 2;
(...)
sp.Children.Add(line);
我应该使用INotifyPropertyChanged接口吗?这是最正确的方式吗?
答案 0 :(得分:0)
没有必要使用INotifyPropertyChanged。
只需创建一个绑定和setbinding到该行的X2Property。
StackPanel sp = new StackPanel();
sp.Orientation = Orientation.Vertical;
Line line = new Line();
line.X1 = 0;
var bind = new Binding()
{
Source = sp,
Path = new PropertyPath("ActualWidth")
};
BindingOperations.SetBinding(line, Line.X2Property, bind);
line.StrokeThickness = 2;
line.Stroke=Brushes.Black;
line.Margin=new Thickness(10);
sp.Children.Add(line);
答案 1 :(得分:0)
具有绑定X2
属性且StrokeThickness
为2的Line的替代方法是一个Height
为2的Rectangle。其宽度自动设置为StackPanel宽度。
var sp = new StackPanel
{
Orientation = Orientation.Vertical
};
...
var line = new Rectangle
{
Height = 2,
Fill = Brushes.Black
};
sp.Children.Add(line);