从示例创建wpf UIElement

时间:2011-05-13 09:16:43

标签: c# wpf uielement

我正在寻找创建一堆将要共享一些属性的矩形,而其他一些属性则会有所不同。这一切都是在代码隐藏中完成的,很明显很有可能在没有通过复制和粘贴技巧打破汗水的情况下做到这一点,但本着使我的代码更优雅的精神;是否有可能有这样的样本矩形

Rectangle sampleRect = new Rectangle(){Stroke = strokebrush,Margin = new Thickness(5)};

并在其后使用不同的高度和宽度属性建模其他矩形?

更新感谢您的回答,我实际上正在寻找更多CSS /风格的东西......

2 个答案:

答案 0 :(得分:0)

您可以使用代表Rectangle参数的类,并使用DataTemplate将您的班级转换为XAML中的Rectangle

并且您的类将具有默认的Strock和Margin,您可以覆盖高度和宽度

答案 1 :(得分:0)

你可以将它包装在一个方法中,就像这样(假设strokebrush是某种局部字段)

private static Rectangle RectangleBuilder(int height, int width)
{
   Rectangle sampleRect = new Rectangle()
   {
       Stroke = strokebrush,
       Margin = new Thickness(5),
       Height = height,
       Width = width
   };
   return sampleRect;
}