I开发者_开发问答 have a WPF usercontrol which contains a number of textboxes and buttons. Currently these textboxes and buttons are all created and loaded dynamically into an ItemsControl through the code behind, whenever an instance of the control is created. The only hard-coded XAML is the declaration of the ItemsControl.
This can be a bit sluggish sometimes. Would it be any quicker if I got rid of the ItemsControl and hard-coded the textboxes and buttons into the usercontrol's XAML?
It's generally better to follow best practices for the platform you're working on; generating items 'by hand' in code-behind certainly isn't one of them in WPF. Look into using DataTemplates and leave the hard work for the framework. It's not hard-coding - you will still provide items (in code behind if you must, but preferably through bindings), and the ItemsControl will 'dress up' the items provided into its ItemsSource with the proper DataTemplates. This will usually work faster, even if only because virtualization is handled automatically (depending on the actual control you're using, but most ItemsControls do).
Two options: Use code to generate the object graph, or use XAML.
Code generated:
1) The compiler converts your code to IL
2) Your IL is interpreted at runtime by the CLR
3) Your object graph is created as your code executes
XAML generated (essentially a mix of code and XAML that makes up your UserControl):
1) The compiler converts the code part to IL and the XAML to BAML
2) Your IL is interpreted at runtime
3) Your class is constructed from the BAML file at runtime
4) Unicorns and magic merge the two
The second version is actually a little slower at runtime (or so I've heard). Of course, this is a big simplification of the process, but you can see that the second version is a little more involved and has more unicorn content. But the fact is that they are, from a UI perspective, pretty much equivalent.
I think your slugishness might be caused by something else. Perhaps you're actually seeing the JIT lag from first execution, or other factors in your code may be causing the process to take longer.
Regardless I'd suggest you create your WPF forms the WPF way. Use binding, and if you need to dynamically create your UI look into ItemsControls and DataTemplates. Its much easier than you'd think.
Well certainly there is no great speed difference, but for development, debugging etc code behind is little better.
Try Xaml Generator, and see it for yourself.
精彩评论