Search code examples
c#wpfdata-bindingcomboboxitemcontainerstyle

WPF unable to select enabled item within ComboBox


I'm trying to create a ComboBox with some items within the selection list enabled and others disabled. Visually, I'm able to do this but when I select an item that is visually enabled, nothing happens.

XAML:

<ComboBox ItemsSource="{Binding EndpointModel.DisplayFormat}" 
          VerticalAlignment="Center" Margin="0,0,10,0" 
          SelectedItem="{Binding EndpointModel.SelectMediaFormat}">
     <ComboBox.ItemContainerStyle>
          <Style TargetType="ComboBoxItem">
              <Setter Property="IsEnabled" Value="{Binding IsEnabled}" />
          </Style>
     </ComboBox.ItemContainerStyle>
     <ComboBox.ItemTemplate>
          <DataTemplate>
              <ComboBoxItem>
                 <TextBlock Text="{Binding Name}" />
              </ComboBoxItem>
          </DataTemplate>
     </ComboBox.ItemTemplate>
</ComboBox>

enter image description here

When I click on the selected item above, nothing happens - EndpointModel.SelectMediaFormat is not executed.

The moment I remove the ComboBox.ItemTemplate stanza, I can successfully select any enabled item, i.e.

<ComboBox ItemsSource="{Binding EndpointModel.DisplayFormat}" 
          VerticalAlignment="Center" Margin="0,0,10,0" 
          SelectedItem="{Binding EndpointModel.SelectMediaFormat}">
     <ComboBox.ItemContainerStyle>
          <Style TargetType="ComboBoxItem">
              <Setter Property="IsEnabled" Value="{Binding IsEnabled}" />
          </Style>
     </ComboBox.ItemContainerStyle>
</ComboBox>

enter image description here

As you can see, i'm displaying the object reference. I can't figure out how to replace the above with the actual Names.

I'm quite new at WPF, as you can imagine :-)

Any suggestions would be appreciated.


Solution

  • Try using the DisplayMemberPath property to Name (The property that you want to display).

    <ComboBox ItemsSource="{Binding EndpointModel.DisplayFormat}" 
              VerticalAlignment="Center" Margin="0,0,10,0" 
              SelectedItem="{Binding EndpointModel.SelectMediaFormat}"
              DisplayMemberPath="Name">
         <ComboBox.ItemContainerStyle>
              <Style TargetType="ComboBoxItem">
                  <Setter Property="IsEnabled" Value="{Binding IsEnabled}" />
              </Style>
         </ComboBox.ItemContainerStyle>
    </ComboBox>