默认情况下,在ListView中选择第一项,MVVM,C#

esi*_*ned 2 c# wpf xaml listview mvvm

我正在编写一些程序,可以选择设备然后进行配置.我实现了列出所有设备的ListView.我喜欢默认选择第一个设备.怎么做?我尝试在StackOverflow和Google上找到几个解决方案,但没有运气.

这是我在XAML中的代码:

<ListView Name="lvdevices" Grid.Row="1" Margin="2" ItemsSource="{Binding devicelist}" SelectionMode="Single" SelectedItem="{Binding SelectedDevice}" DataContext="{Binding }">
       <ListView.View>
                <GridView x:Name="gridDevices">
                    <GridViewColumn>
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <CheckBox Tag="{Binding ID}" IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}}, Path=IsSelected}"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn x:Name="DeviceId" Header="DeviceId" DisplayMemberBinding="{Binding DeviceId}" Width="50"/>
                    <GridViewColumn x:Name="NameId" Header="NameId" DisplayMemberBinding="{Binding NameId}" Width="100"/>
                    <GridViewColumn x:Name="ManufacturerId" Header="ManufacturerId" DisplayMemberBinding="{Binding ManufacturerId}" Width="150"/>
               </GridView>
      </ListView.View>
</ListView>
Run Code Online (Sandbox Code Playgroud)

我不知道如何实现连接时默认选择第一个项目.还有可能找不到任何设备,那么呢?请帮忙!如果有问题请询问.

Mik*_*son 5

When you populate your devicelist, you can set the SelectedDevice to be the first item in the device list, or null if there is nothing in the list.

using System.Linq;

...

SelectedDevice = devicelist.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

假设这个SelectedDevice实现INotifyPropertyChanged,那么应该选择视图中的第一个项目.