Question

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.

Was it helpful?

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.

OTHER TIPS

Inheritance should take care of that for you. In other words, if you have two user controls, the first one with a basic element of ListView (not UserControl) and the other of ListViewItem (again, not UserControl), and you make sure they extend ListView and ListViewItem respectively in the .cs code, the following should work equally:

ListView lv = new ListView();
lv.Items.Add(new ListViewItem());

or

MyListView mlv = new MyListView();
mlv.Items.Add(new myListViewItem()); //If your myListView extends ListView, and myListViewItem extends ListViewItem in your user control files, of course

In case you are looking for a XAML solution, you should import your namespace at the top

xmlns:myControls="WhateverYourNamespaceAndAssemblyAre"

and on you page/window/whatever

<myControls:myListView>
    <myControls:myListViewItem/>
    <myControls:myListViewItem/>
</myControls:myListView>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top