简体   繁体   English

在页面加载时在ListView中选择项目

[英]Item is being selected in ListView on page load

I have a ListView in my xaml, and it's ItemsSource and SelectedItem property is binded to a ViewModel. 我的xaml中有一个ListView ,它的ItemsSource和SelectedItem属性绑定到了ViewModel。

Xaml Xaml

<ListView ItemsSource="{Binding SitesCollection}" SelectedItem="{Binding SelectedSite, Mode=TwoWay}">
    <ListView.ItemTemplate>
        <DataTemplate>
              <TextBlock Text="{Binding url}"></TextBlock>
         </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

ViewModel 视图模型

public ObservableCollection<AWRestrictedSite> _SitesCollection;
public ObservableCollection<AWRestrictedSite> SitesCollection
{
     get
     {
          //populate collection
          return _SitesCollection;
     }
}

public AWRestrictedSite _SelectedSite;
public AWRestrictedSite SelectedSite
{
      get
      {
          return _SelectedSite;
      }
      set
      {
          _SelectedSite = value;
          //do some stuff
      }
 }

For some reason when the page loads, it selects the first item in the ListView. 由于某种原因,页面加载时会选择ListView中的第一项。 Here is what happens when the page loads: 页面加载时会发生以下情况:

  1. Get inside SitesCollection is being called, (which populates the listview and returns the collection). Get内部调用SitesCollection(填充列表视图并返回集合)。
  2. Get inside SelectedSite is called, which returns null 获取内部SelectedSite的调用,该方法返回null
  3. Set inside SelectedSite is called which sets the value to the first item 在SelectedSite内部进行设置的调用将其值设置为第一项

Does anyone know why this could be happening? 有谁知道为什么会这样?

Its a two way bind, and when loaded, ListView (I think) selects the first item in its bound collection. 它是双向绑定,并且在加载时, ListView (我认为)在其绑定集合中选择第一个项目。 Try adding a Loaded method to the ListView and setting the SelectedItem in there. 尝试将Loaded方法添加到ListView并在其中设置SelectedItem This should happen after the first item is selected. 这应该选择第一个项目之后发生。

当我们将ListViewSelectedItem设置为ItemsSourceCollection.FirstOrDefault()时,通常会发生这种情况

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

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