Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create ComboBox like UserControl in WPF

I'm trying to build an usercontrol wich is able to take elements from XAML like this:

            <ComboBox >
                <ComboBoxItem />
                <ComboBoxItem />
                <ComboBoxItem />
            </ComboBox>

In the ComboBox, you can just add the Items between the ComboBox tags, and I would like to copy this, but I don't know where to start.

Finished it should look like this:

    <cis:ReportControl Grid.Row="3">
            <cis:ReportItem />
    </cis:ReportControl>

In the cis:ReportControl, there are some Buttons and a ComboBox, and basically I only want to feed the ComboBox with Items.

The Report Item is just a ComboBoxItem with some extra properties.

Edit:

I've implemented it according to @Snowbears answer, but the problem now is that the control has itself as an item. I think this is because I have some content, and by defining the ContentProperty to my ComboBox, it is redirected into the Box. What can I do to avoid this?

Edit II:

It fully works now with this:

    private ItemCollection reportItems;
    public ItemCollection ReportItems
    {
        get
        {
            if (reportItems == null)
            {
                reportItems = this.ComboBoxReports.Items;
            }
            return reportItems;
        }
    }

with the [ContentProperty("ReportItems")] Attribute. ComboBoxReports is the ComboBox in the Control, and I had to inherit from ItemsControl to get it to work.

like image 793
Tokk Avatar asked Oct 12 '22 14:10

Tokk


1 Answers

  1. You should create property in your UserControl which will expose something implementing IList interface. Let's say this property will be named ReportItems. This property should not have setter and it should be initialized in UserControl itself either in constructor in by field initialization on backing field.
  2. UserControl should be marked with ContentProperty attribute with your property name (ReportItems)
  3. Internal combobox should have it's ItemsSource bound to UserControl's ReportItems property
like image 123
Snowbear Avatar answered Oct 15 '22 19:10

Snowbear