Search code examples
wpflistviewuser-controlslistviewitem

How do I make user controls for both ListView and ListViewItem work with each other?


I have all the styling, triggers, etc. down for ListView and ListViewItem, and I want to turn them into user controls. How do I make sure that these two "match up" with each other, so that MyListView accepts MyListViewItems as content? Also, considering that I must end the ListView tag by the end of the user control XAML file, I am not sure how I would add items to it.


Solution

  • If you want them to be reusable with different data sets, especially through binding, you should stay away from UserControls and just make custom controls derived from the original types. In that case you create a standalone MyListView.cs and MyListViewItem.cs and all of the XAML for the controls goes into default Styles (usually also containing a ControlTemplate) in Themes/Generic.xaml. You can see an example of this setup by just adding a WPF Custom Control to your WPF project from Add New Item.

    Once you've created the .cs files for your custom controls you just need to override a few methods from the base ItemsControl to use MyListViewItem as the item container control. The ListView would end up like this:

    public class MyListView : ListView
    {
        static MyListView()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(MyListView), new FrameworkPropertyMetadata(typeof(MyListView)));
        }
    
        protected override DependencyObject GetContainerForItemOverride()
        {
            return new MyListViewItem();
        }
    
        protected override bool IsItemItsOwnContainerOverride(object item)
        {
            return item is MyListViewItem;
        }
    }
    

    You can now use your custom MyListView exactly as you would a normal ListView, including binding to ItemsSource.