Pyranth Pyranth - 20 days ago 14
C# Question

Cannot select item in ComboBox in UWP

I created ComboBox binded with ObservableCollection. Here is the code.

XAML

<StackPanel HorizontalAlignment="Center"
Grid.Row="0">
<TextBlock Text="Choose a city" />
<ComboBox x:Name="CityComboBox"
SelectionChanged="CityComboBox_SelectionChanged"
ItemsSource="{x:Bind cities}"
HorizontalAlignment="Center"
VerticalAlignment="Top">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="data:City">
<ComboBoxItem Content="{x:Bind name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>


C# class

public class Grad
{
public String imeGrada { get; set; }
public ArrayList arr1 { get; set; }
public List<A> list1 { get; set; }

public City()
{
name = "NewYork";
arr1= new ArrayList();
list1 = new List<A>();
}


When I run the application, I cannot select ComboBoxItem clicking on the center of it, but only on the edge of the item. If I use ComboBox without bining but hardcoding items, it works properly.

Image

Selecting only works if clicked on green area. Clicking on red area does nothing.

What causes this and how can I fix it?

Thanks in advance!

Answer

You shouldn't use the ComboBoxItem in your DataTemplate since the content of the DataTemplate will be automatically added inside another ComboBoxItem. In your solution there is ComboBoxItem inside another ComboBoxItem.

So solution for your problem should be something like that:

<ComboBox.ItemTemplate>
    <DataTemplate x:DataType="data:City">
        <TextBlock Text="{x:Bind name}" />
    </DataTemplate>
</ComboBox.ItemTemplate>