【发布时间】:2021-06-12 21:02:59
【问题描述】:
我想为我的 WPF 页面添加一些矩形,这些矩形应该有圆角。为了将一些矩形带到页面上,而不必在 xaml 中编写每一个矩形,我决定在代码中使用循环来实现。 我试过这个:
for (int i = 0; i < 5; i++)
{
Rectangle rect = new Rectangle();
rect.Fill = System.Windows.Media.Brushes.Green;
var style = new Style(typeof(Border));
style.Setters.Add(new Setter(Border.CornerRadiusProperty, new CornerRadius(12.0, 0, 0 , 0)));
rect.Resources.Add(typeof(Border), style);
Grid.SetColumn(rect, 1);
Grid.SetRow(rect, 1);
mainGrid.Children.Add(rect);
}
但我的矩形的角半径不会改变。你有什么建议吗?
提前感谢您的帮助!
【问题讨论】:
-
您可以为此目的使用styles and templates。从代码隐藏中改变任何东西都是坏主意
-
this answer 和 this article 应该可以帮到你
-
感谢您的回答!刚刚注意到@Blindy 说的有'RadiusX'和'RadiusY'。这效果很好。不过我会看看 MVVM,因为我还没有。
标签: c# wpf rectangles rounded-corners cornerradius