Comboxbox auto select first item when data is available
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:Res开发者_JAVA技巧olutionConverter 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>
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">
....
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
Here is how to do it in code:
Items.CollectionChanged += (sender, e) =>
{
if (!Items.Contains(Selected))
{
Selected = Items.FirstOrDefault();
}
};
Items
is an ObservableCollection
that may be updated. Selected
is a two-way property of the selected item. This code should be placed in the constructor of your view-model.
精彩评论