Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying to create a custom combobox to use in wpf. Doing it in xaml didn't work. I can do it if I make it a user control but I'm trying to inherit from combobox itself.

I then tried doing it programmatically like this:

C#
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

public class customcombobox:ComboBox
{
    public customcombobox()
    {
        Binding binding = new Binding();
        binding.Source = somefunction(); //returns a list
        binding.Converter = new Converter(); //converts the data
        this.SetBinding(ComboBox.ItemsSourceProperty, binding);
    }
}


I get an error in the xaml telling me I cannot create an instance.
Posted

The problem is that you're attempting to modify the control before it has been initialized. To get it to work all you have to do is have the constructor inherit from the base class:

public customcombobox() : base()
{
    Binding binding = new Binding();
    binding.Source = somefunction(); //returns a list
    binding.Converter = new Converter(); //converts the data
    this.SetBinding(ComboBox.ItemsSourceProperty, binding);
}
 
Share this answer
 
I figured out my problem. Didn't need to have the constructor inherit from the base it said it was redundant. The problem was actually in my converter. I use the same converter elsewhere in my code but when using it in the xaml it doesn't send it as a list it sends each individual item in the list and converts and returns.

In this case the converter actually sends it in as a list. I needed to have the converter check if it was a list and return a converted list.

I looked here to work out my answer. Using converters to aggregate a list in a ListView[^]

My code ended up being something like this.

XML
Type ValueType = value.GetType();
if (ValueType.Name == typeof(List<>).Name) // Check if we're dealing with a list
{
    List<String> dummy= new List<string>();  //create a new list to return
    foreach (var item in (IList)value //iterate through the list
    {
        //calling a function to convert data and add it to the list
        dummy.Add(somefunction((ItemType)item));
    }
    //return the new list
    return dummy;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900