views:

49

answers:

2

I have this very simple Combobox in my XAML:

<ComboBox Name="cmb1" Width="200" Height="23" ItemsSource="{Binding}" />

and this is my code behind:

public class Test //: System.Windows.DependencyObject
{
    public string Name { get; set; }

    public override string ToString() { return Name; }
}

public MainWindow()
{
    InitializeComponent();

    var col = new ObservableCollection<Test>();
    cmb1.DataContext = col;
    col.Add(new Test { Name = "A" });
    col.Add(new Test { Name = "B" });
    col.Add(new Test { Name = "C" });
    col.Add(new Test { Name = "D" });
}

As long as Test class is NOT inherited from DependencyObject everything is fine. But when it is inherited, ComboBox does not show current item when it is not expanded.
Current Item is selected when I click on ComboBox and see its drop-box. alt text

+1  A: 

This was the answer by karmicpuppet in a now deleted question:

This is interesting. Well, I've looked at the ComboBox class using Reflector and I see that in the ComboBox.UpdateSelectionBoxItems() method, part of it does something like:

If ItemTemplate, ItemTemplateSelector, and ItemStringFormat were not set, and selected item is a DependencyObject that is not derived from UIElement, call the ExtractString(selectedItem) method.

The ComboBox.ExtractString(dObj) method, on the other hand, apparently checks to see if the selectedItem (which is a DependencyObject) is either a TextBlock, a Visual, or a TextElement to display the appropriate string. Otherwise, it will return string.Empty.

So the easiest solution would be to set this on the Combobox:

ItemStringFormat="{}{0}"
bitbonk
That is a relief to hear ComboBox deals with DependencyObject and other classes separately. Now it makes more sense that why it does not call ToString() method of the Test class when it is a DependencyObject. Thanks.
shayan
+1  A: 

Related: see this answer I have on another question. Based on that, I think it maybe a bug. And if you do at least one of the following, the selection should work:

  1. Specify an ItemTemplate.
  2. Specify an ItemTemplateSelector.
  3. Specify an ItemStringFormat.
  4. Derive the item from UIElement.

EDIT: Question got deleted. Just see my explanation on the other answer for this question.

karmicpuppet
Oh crap, the question got deleted. But yeah, just see what bitboink posted. That should explain it. =)
karmicpuppet