【问题标题】:Select first item in ListView by default, MVVM, C#默认选择ListView中的第一项,MVVM,C#
【发布时间】:2015-11-04 16:36:16
【问题描述】:

我正在编写一些程序,可以在其中选择设备并稍后对其进行配置。我实现了列出所有设备的 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>

我不知道如何实现连接时默认选择第一项。也有可能找不到设备,那怎么办?请帮忙!如果和问题请询问。

【问题讨论】:

    标签: c# wpf xaml listview mvvm


    【解决方案1】:

    当您填充devicelist 时,您可以将SelectedDevice 设置为设备列表中的第一项,如果列表中没有任何内容,则可以将null 设置为。

    using System.Linq;
    
    ...
    
    SelectedDevice = devicelist.FirstOrDefault();
    

    假设SelectedDevice 实现INotifyPropertyChanged,那么这应该会选择您视图中的第一项。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多