简体   繁体   中英

Select first item in ListView by default, MVVM, C#

I am writing some programm where is possible to select device and later configure it. I implemented ListView where all device are listed. I like that first device is selected by default. How to do that? I try several solution found on StackOverflow and over Google but without luck.

Here is my code in 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>

I dont know how to implement that first item is selected by default when is connected. It is also possibility that no device will found, what then? Please for help! If and question please ask.

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();

Assuming that SelectedDevice implements INotifyPropertyChanged , this should then select the first item on your view.

在ViewModel中,您只需要将SelectedDevice设置为第一项(当然会触发OnPropertyChanged

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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