0

In WPF there are many ways to achieve the same thing. In this example which is better?

<ItemsControl>
    <ItemsControl.Template>
        <ControlTemplate>
            <ScrollViewer>
                <ItemsPresenter />
            </ScrollViewer>
        </ControlTemplate>
    </ItemsControl.Template>
</ItemsControl>

or

<ScrollViewer>
    <ItemsControl />
</ScrollViewer>
6
  • I'm guessing the first if you wanted to use it as a datatemplate for itemscontrol's
    – user13070
    Jun 28, 2012 at 11:39
  • Obviously the one that has less code and more readable is more correct and better until proofed otherwise.
    – Lap
    Jun 28, 2012 at 12:01
  • 3
    Until you actually -need- to template, don't use templating. =)
    – J. Steen
    Jun 28, 2012 at 12:02
  • You forgot the option to use a style to change the template. Jun 28, 2012 at 12:18
  • As in setting the ControlTemplate through a style? I wouldn't think that's really an option you'd consider when you have the choice of these two
    – user13070
    Jun 28, 2012 at 12:36

2 Answers 2

2

Until you actually -need- to template, don't use templating. =)

That said, my highly personal rule of thumb is that if I'm repeating the same work more than two times (i.e., three and up) I probably need to template or implement some other lovely DRY principle.

0
2

This would be a better solution

<ItemsControl>
    <ItemsControl.Template>
        <ControlTemplate>
            <ScrollViewer CanContentScroll="True">
                <StackPanel IsItemsHost="True" />
            </ScrollViewer>
        </ControlTemplate> 
    </ItemsControl.Template>
</ItemsControl>

This is because unlike ItemsControl or ItemsPresenter, StackPanel supports the IScrollInfo interface, and therefore you could exert a lot more control over how your items are scrolled.

http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.iscrollinfo.aspx

4
  • assuming you want your items presented in a stackpanel. also, i'm not sure fixed height is a better solution? well I prefer not to anyway
    – user13070
    Jun 28, 2012 at 13:58
  • If you are going to use an ItemsControl, use a VirtualizingStackPanel instead. It's indicated here: Optimizing WPF Application Performance msdn.microsoft.com/en-us/library/aa970683(v=vs.85).aspx
    – Xcalibur37
    Jun 29, 2012 at 0:52
  • An Itemscontrol as standard uses a non-virtualising stack panel by default, which is reflected in my answer. You would only use a virtualising stack panel if you wanted virtualisation behaviour.
    – Dean Chalk
    Jun 29, 2012 at 8:19
  • The fixed height was unecessary, and I forgot to remove it from my demo before I copied my code. Have edited it out now
    – Dean Chalk
    Jun 29, 2012 at 8:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.