其长度自行调整为父级面板的ActualWidth属性(数据绑定)

时间:2016-06-03 01:15:11

标签: c# wpf data-binding

我有一个垂直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接口吗?这是最正确的方式吗?

2 个答案:

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