Home > Mobile >  WPF combobox - select the first item as default
WPF combobox - select the first item as default

Time:12-10

I'm looking for a possibility to set the first item in my combobox as the default value.

I have my view (XAML) with the combobox:

<ComboBox  ItemsSource="{Binding SiteScripts, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" 
           SelectedValue="{Binding SelectedSiteScriptId}" 
           SelectedIndex="0"  SelectedValuePath="Id" 
           DisplayMemberPath="Name"  Background="AliceBlue" 
           Margin="5,10,10,540" Width="100" Height="50"/>

I am binding to my list from the view model in the ItemsSource property of the combobox and my SelectedValue is bound to the ID property item:

public List<SiteCreateMachineScripts> SiteScripts
{
        get { return _siteScripts; }
        set
        {
            _siteScripts = value;
            NotifyOfPropertyChange();
        }
}

public int SelectedSiteScriptId
{
    get { return _selectedSiteScriptId; }
    set
    {
        _selectedSiteScriptId = value;
        NotifyOfPropertyChange();
    }
}

I already tried to set the SelectedIndex = 0 but it didn't work

Thanks for any advice :)

CodePudding user response:

As commented you should do it better in ViewModel.

Technically you can use a style and Load event to set SelectedIndex=0, at this moment Binding should already finish setting value from ViewModel and you can set hence new value:

<ComboBox  ItemsSource="{Binding SiteScripts, UpdateSourceTrigger=PropertyChanged}" 
    SelectedValue="{Binding SelectedSiteScriptId}" 
    SelectedValuePath="Id" 
    DisplayMemberPath="Name"  Background="AliceBlue" 
    Margin="5,10,10,540" Width="100" Height="50"/>

    <ComboBox.Style>
        <Style TargetType="{x:Type ComboBox}">
            <Style.Triggers>
                <EventTrigger RoutedEvent="Loaded">
                    <BeginStoryboard>
                        <Storyboard>
                            <Int32Animation Storyboard.TargetProperty="SelectedIndex" To="0"/>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>

</ComboBox>

CodePudding user response:

General processing is selected by default

public class ViewModel
{
    public List<SiteCreateMachineScripts> SiteScripts
    {
        get { return _siteScripts; }
        set
        {
            _siteScripts = value;
            NotifyOfPropertyChange();
        }
    }

    public int SelectedSiteScriptId
    {
        get { return _selectedSiteScriptId; }
        set
        {
            _selectedSiteScriptId = value;
            NotifyOfPropertyChange();
        }
    }

    public ViewModel()
    {
        SiteScripts = GetList(); // init list
        SelectedSiteScriptId = SiteScripts.First().Id;
    }
}
  • Related