繁体   English   中英

在WPF中将Combobox的SelectedIndex设置为0

[英]set SelectedIndex of Combobox in WPF to 0

我在运行时将Collection绑定到组合框,我想将Index设置为0。找不到所需的直接答案。

_stationNames = new ObservableCollection<string>(_floorUnits.Unit.Select(f => f.Name));
_stationNames.Insert(0, "All");
stationsComboBox.ItemsSource = _stationNames;
stationsComboBox.SelectedIndex = 0;//Doesn;t work

Xaml

<ComboBox x:Name="stationsComboBox" Grid.Row="1" Grid.Column="1" Text="{Binding Name}"
                  SelectionChanged="StationComboBoxSelectionChanged" VerticalAlignment="Center" Margin="3"
                   SelectedIndex="0"/>

听起来您像在使用WinForms一样尝试使用它。 WPF是与众不同的野兽,并且在绑定方面功能更强大。

我建议阅读MVVM以获得WPF的最大好处。 通过将XAML绑定到视图模型类(而不是尝试将代码隐藏在后台代码中),您将发现可以以更大的灵活性来完成所需的工作,而无需编写大量代码。

例如:给定以下虚拟机:

public class MyViewModel: INotifyPropertyChanged
{

    public ObservableCollection<string> StationNames
    {
        get;
        private set;
    }

    public Something()
    {
        StationNames = new ObservableCollection<string>( new [] {_floorUnits.Unit.Select(f=>f.Name)});
        StationNames.Insert(0, "All");
    }

    private string _selectedStationName = null;
    public string SelectedStationName
    {
        get
        {
            return _selectedStationName;
        }
        set
        {
            _selectedStationName = value;
            FirePropertyChanged("SelectedStationName");
        }
    }

    private void FirePropertyChanged(string propertyName)
    {
        if ( PropertyChanged != null )
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

您可以将视图的(XAML形式)DataContext设置为ViewModel的实例,并将组合框定义更新为:

<ComboBox x:Name="stationsComboBox" Grid.Row="1" Grid.Column="1"
                  ItemsSource="{Binding Path=StationNames}" SelectedItem={Binding Path=SelectedStationName} VerticalAlignment="Center" Margin="3"
                   SelectedIndex="0"/>

从此处开始,只要组合框选择发生更改,VM的SelectedStationName就会更新以反映当前选择,并且在VM代码中的任何位置,设置VM的SelectedStationName都会更新组合的选择。 (即实现“重置”按钮等)

但是,通常,按照您的建议,我将直接绑定到Units集合。 (如果VM本身可以查看/编辑,则可以从单元派生。)在任何情况下,它都应该为您提供一些起点,开始研究WPF绑定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM