BitmapFrame in WPF ComboBox

2019-08-20 10:00发布

问题:

I have a dialog that lets the user pick a custom icon. Loaded icons are displayed in a combobox in which the user makes the selection. Here is the XAML code for the combobox:

<ComboBox 
    Style="{DynamicResource IconComboBox}"
    ItemTemplate="{StaticResource IconTemplate}"
    ItemsSource="{Binding Icons,
        RelativeSource={RelativeSource FindAncestor, 
            AncestorType={x:Type UserControl}}}"
    SelectedItem="{Binding Icon}"
    />
  • Icons is a property that returns an array of BitmapFrame.
  • Icon is a property for the currently selected.

What currently doesnt work is that when I through the code behind set the Icon property (for example, when displaying which Icon the user picked the last time the dialog was shown), the Combobox selection is just blank. As if I had set the property to null before calling OnPropertyChanged.

My current theory is that WPF cannot compare BitmapFrames, so when walking through the list it fails to determine any of the icons there the "equal" and thus assumes null.

In short; what is the best way to through code behind set the currently selected item, which is a BitmapFrame, in a combobox?

回答1:

You can use SelectedItem or SelectedIndex in the code behind to set the currently selected item!