Search code examples
c#wpfcomboboxdatatrigger

SelectedIndex DataTrigger not working in Combobox


What I want to do is if a combobox has only 1 item then it gets preselected. I tried usind DataTriggers but its not working for 'SelectedIndex' property.But when I set 'IsEnabled' property to false its working and disable the combobox.

Below is my code:

<ComboBox  Name="WarehouseCombo" 
      ItemsSource="{Binding Path=WarehouseList}"
      SelectedValue="{Binding Warehouse,Mode=TwoWay}"
      Text="{Binding Path=TxtWarehouse,Mode=TwoWay}">
        <ComboBox.Style>
              <Style TargetType="{x:Type ComboBox}">
                    <Style.Triggers>
                         <DataTrigger
                              Binding="{Binding Path=Items.Count, ElementName=WarehouseCombo}" Value="1">
                                  <Setter Property="SelectedIndex" Value="0" />
                          </DataTrigger>
                     </Style.Triggers>
               </Style>
         </ComboBox.Style>
 </ComboBox>

Please help me as why is this happening in 'SelectedIndex' case.


Solution

  • Don't use the SelectedIndex property. Instead, use the SelectedItem property. One way to fulfil your requirements is to declare a base class for your data collection. Try something like this:

    public WarehouseList : ObservableCollection<WarehouseItems>
    {
        private T currentItem;
    
        public WarehouseList() { }
    
        public T CurrentItem { get; set; } // Implement INotifyPropertyChanged here
    
        public new void Add(T item)
        {
            base.Add(item);
            if (Count == 1) CurrentItem = item;
        }
    }
    

    Now if you use this class instead of a standard collection, it will automatically set the first item as selected. To make this work in the UI, you simply need to data bind this property to the SelectedItem property like this:

    <DataGrid ItemsSource="{Binding WarehouseList}" 
        SelectedItem="{Binding WarehouseList.CurrentItem}" />