Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comboxbox auto select first item when data is available

Tags:

c#

wpf

xaml

I am looking for way to select the first item when data became available. But if no data in the source , then do not select. How to do it ? I am very new to WPF.

<ComboBox Grid.Row="5" Grid.Column="1"
          IsEditable="False"
          ItemsSource="{Binding Source={x:Static l:DirectXResolution.Resolutions}}"
          ToolTip="Resolutions">
    <ComboBox.Resources>
        <l:ResolutionConverter x:Key="resolutionConverter"/>
    </ComboBox.Resources>
    <ComboBox.Text>
        <MultiBinding Converter="{StaticResource resolutionConverter}">
            <Binding Path="GameWidth" Mode="OneWayToSource"/>
            <Binding Path="GameHeight" Mode="OneWayToSource"/>
        </MultiBinding>
    </ComboBox.Text>
</ComboBox>
like image 350
dan_l Avatar asked Sep 29 '11 23:09

dan_l


2 Answers

The easiest way is to use SelectedIndex. Please, check the code below.

<ComboBox Grid.Row="5" Grid.Column="1"
          IsEditable="False"
          ItemsSource="{Binding Source={x:Static l:DirectXResolution.Resolutions}}"
          ToolTip="Resolutions"
          SelectedIndex="0">
....
like image 83
Jin-Wook Chung Avatar answered Oct 22 '22 17:10

Jin-Wook Chung


DirectXResolution.Resolutions must be ObservableCollection<T> otherwise your ComboBox will not be updated when the data becomes available. You can use CollectionChanged event of ObservableCollection<T> to select the first item.

If DirectXResolution.Resolutions is not ObservableCollection, create a wrapper for this collection and inherit INotifyCollectionChanged

like image 38
evpo Avatar answered Oct 22 '22 18:10

evpo