WPF中如何不使用Grid在Canvas中自由绘制大量图形集合
动态创建带定位输入框的矩形集合解决方案
需求
- 用户点击Canvas时,每次生成一个矩形,同时创建8个用于输入矩形尺寸的TextBox
- TextBox需相对矩形边框精准定位,每个矩形与对应的TextBox构成独立的图形集合
遇到的问题
- 最初使用Grid动态添加元素时,TextBox默认居中显示,若要修正定位必须设置行列,但业务场景不需要这种布局逻辑
- 期望实现完全动态的自由定位,且全程通过代码实现无需XAML,尝试StackPanel等其他布局控件后无法满足需求
解决方案
采用嵌套Canvas的Grid结构实现:每个矩形及其关联的TextBox都放入独立的Canvas中,利用Canvas的SetLeft和SetTop方法实现精准定位;再将这些承载独立图形集合的Canvas添加到Grid中,统一管理所有图形集合。这种方式既保留了Canvas的自由定位能力,又通过Grid实现了多元素的整体管理。
实现代码
Grid DynamicGrid = new Grid(); DynamicGrid.HorizontalAlignment = HorizontalAlignment.Left; DynamicGrid.VerticalAlignment = VerticalAlignment.Stretch; DynamicGrid.ShowGridLines = true; DynamicGrid.Background = new SolidColorBrush(Colors.LightSteelBlue); var c1 = new Canvas(); var c2 = new Canvas(); //--------------------- Canvas1 子元素 --------------------- Rectangle c1Rectangle = new Rectangle { Width = 100, Height = 100, Fill = new SolidColorBrush(Color.FromRgb(255, 0, 0)), StrokeThickness = 2, Stroke = Brushes.Black }; Canvas.SetLeft(c1Rectangle, 0); Canvas.SetTop(c1Rectangle, 0); TextBlock c1Textbox = new TextBlock(); c1Textbox.Width = 50; c1Textbox.Height = 50; c1Textbox.Text = "Text1"; c1Textbox.FontSize = 14; c1Textbox.FontWeight = FontWeights.Bold; c1Textbox.Foreground = new SolidColorBrush(Colors.White); c1Textbox.VerticalAlignment = VerticalAlignment.Top; Canvas.SetLeft(c1Textbox, 10); Canvas.SetTop(c1Textbox, 10); //--------------------- Canvas2 子元素 --------------------- Rectangle c2Rectangle = new Rectangle { Width = 100, Height = 100, Fill = new SolidColorBrush(Colors.LightBlue), StrokeThickness = 2, Stroke = Brushes.Red }; Canvas.SetLeft(c2Rectangle, 420); Canvas.SetTop(c2Rectangle, 220); TextBlock c2Textbox = new TextBlock(); c2Textbox.Width = 50; c2Textbox.Height = 50; c2Textbox.Text = "Text2"; c2Textbox.FontSize = 14; c2Textbox.FontWeight = FontWeights.Bold; c2Textbox.Foreground = new SolidColorBrush(Colors.Black); c2Textbox.VerticalAlignment = VerticalAlignment.Top; Canvas.SetLeft(c2Textbox, 440); Canvas.SetTop(c2Textbox, 240); c1.Children.Add(c1Rectangle); c1.Children.Add(c1Textbox); c2.Children.Add(c2Rectangle); c2.Children.Add(c2Textbox); DynamicGrid.Children.Add(c1); DynamicGrid.Children.Add(c2); this.Content = DynamicGrid; this.Show();
内容的提问来源于stack exchange,提问作者user1019042
相关产品推荐
相关产品推荐

