簡體   English   中英

WPF combobox - select 默認為第一項

[英]WPF combobox - select the first item as default

我正在尋找將 combobox 中的第一項設置為默認值的可能性。

我對 combobox 有我的看法(XAML):

<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"/>

我從 combobox 的ItemsSource屬性中的視圖 model 綁定到我的列表,並且我的SelectedValue綁定到ID屬性項:

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

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

我已經嘗試設置SelectedIndex = 0但它不起作用

感謝您的任何建議:)

如評論所述,您應該在 ViewModel 中做得更好。

從技術上講,您可以使用樣式和Load事件來設置SelectedIndex=0 ,此時Binding應該已經完成了 ViewModel 的設置值,因此您可以設置新值:

<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>

默認選擇常規處理

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM