简体   繁体   中英

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...

you could have Class that represents your Rectangle parameters and use DataTemplate to convert your class into Rectangle in your XAML

and your class will have default Strock and Margin and you can override height and width

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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