【WPF】在UI后台绘图,添加控件

最近遇到一个问题,需要在界面上动态生成一些控件/图,于是学习了一些在UI后台用C#代码绘图、添加控件的方法,下面放个小例子:

/// <summary>
    /// TimeLine.xaml 的交互逻辑
    /// </summary>
    public partial class TimeLine : UserControl
    {
        public TimeLine()
        {
            InitializeComponent();
            DataContext = new TimeLineViewModel();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //绘制二次方贝塞尔曲线段,并将其添加到Canvas控件中
            Path path = new Path
            {
                Stroke = Brushes.DarkRed,
                StrokeThickness = 10,
            };
            PathGeometry pathGeometry = new PathGeometry();
            PathFigure pathFigure = new PathFigure
            {
                //起节点
                StartPoint = new Point(10, -30),
            };
            QuadraticBezierSegment qbs = new QuadraticBezierSegment
            {
                //控制节点
                Point1 = new Point(100, -100),
                //终节点
                Point2 = new Point(200, -30),
            };
            pathFigure.Segments.Add(qbs);
            pathGeometry.Figures.Add(pathFigure);
            path.Data = pathGeometry;
            can.Children.Add(path);

            //画圆,并将其添加到Canvas控件中
            Path point = new Path
            {
                Data = new EllipseGeometry(new Point(10, -30), 10, 10),
                Fill = Brushes.Red,
            };
            can.Children.Add(point);

            //将TextBlock控件添加到Canvas中指定位置
            TextBlock text = new TextBlock
            {
                Text = "测试",
            };
            text.SetCurrentValue(Canvas.LeftProperty, 20d);
            can.Children.Add(text);

        }
    }
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页