简体   繁体   English

从示例创建WPF UIElement

[英]Creating a wpf UIElement from a sample

I'm looking to create a bunch of rectanges that are going to share some properties and some other properties will be different. 我正在寻找创建一堆将共享某些属性的矩形,而其他一些属性将有所不同。 This is all done in codebehind, and clearly it is very possible to do this without breaking a sweat by copy and paste skills, but in the spirit of making my code more elegant; 这一切都是在代码隐藏中完成的,很显然,这样做很可能不会因复制和粘贴技能而费神,但本着使我的代码更优雅的精神; is it possible to have a sample rectangle like so 是否有可能像这样的示例矩形

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

and model everyother rectangle after that with diefferent height and width attributes? 然后用不同的高度和宽度属性对其他矩形建模?

UPDATE Thanks for the answers, I am actually looking for more of a CSS/style thing... 更新感谢您的回答,我实际上正在寻找更多CSS /样式的东西...

you could have Class that represents your Rectangle parameters and use DataTemplate to convert your class into Rectangle in your XAML 您可以使用表示您的Rectangle参数的Class并使用DataTemplate在XAML中将您的类转换为Rectangle

and your class will have default Strock and Margin and you can override height and width 并且您的班级将具有默认的Strock和Margin,并且您可以覆盖高度和宽度

You could wrap it inside a method, like this (assuming strokebrush is some sort of local field) 您可以将其包装在这样的方法中(假设笔触是某种本地字段)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM