简体   繁体   English

Xamarin.Forms ListView通过代码设置SelectedItem

[英]Xamarin.Forms ListView set SelectedItem by Code

How can I set the SelectedItem of a ListView in my Code?如何在我的代码中设置 ListView 的SelectedItem My problem is, that is isn't highlighted when I preselect an item in my code.我的问题是,当我在我的代码中预选一个项目时,它没有突出显示。 The ListView is defined in the xaml file. ListView 在 xaml 文件中定义。

<ListView ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />

My ViewModel我的视图模型

class MyViewModel
{
    List<MyItem> Items {get; set;}
    MyItem SelectedItem { get; set; }

    public MyViewModel() 
    {
        Items = new List<MyItem>{ ... };
        SelectedItem = Items.First();
    }
}

But when I show the view, it is not highlighting the selected item.但是当我显示视图时,它没有突出显示所选项目。 When I click on an item, it is highlighted and set correctly.当我单击某个项目时,它会突出显示并正确设置。 I've played around with property changed, but this shouldn't have an effect, because the property is set right in the constructor.我试过更改属性,但这应该不会有影响,因为属性是在构造函数中设置的。

In order for your view to update when properties on MyViewModel change, that class must implement INotifyPropertyChanged . 为了在MyViewModel属性更改时更新视图,该类必须实现INotifyPropertyChanged Here's an example: 这是一个例子:

public class MyViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

But importantly you must call OnPropertyChanged in your setters, so your SelectedItem property will need to look something like this: 但是重要的是,您必须在设置器中调用OnPropertyChanged ,因此SelectedItem属性必须看起来像这样:

MyItem _selectedItem;
MyItem SelectedItem {
  get {
    return _selectedItem;
  }
  set {
    _selectedItem = value;
    OnPropertyChanged("SelectedItem");
  } 
}

Lots of good information on MVVM in Xamarin Forms here: From Data Bindings to MVVM Xamarin格式中有关MVVM的很多很好的信息: 从数据绑定到MVVM

In my case was simply this.... (for example select automatically the first element with one element) 就我而言,就是这样...(例如,自动选择具有一个元素的第一个元素)

 protected override async void OnAppearing()
{
    if (MyList.Count == 1)
                {
                    List_CheckPoint.SelectedItem = MyList[0];
                }
    }

You'll need to specify that the xyz binding is two way.您需要指定 xyz 绑定是双向的。

SelectedItem="{Binding xyz, Mode=TwoWay}"

Note your selection might deselect if the collection changes.请注意,如果集合发生变化,您的选择可能会取消选择。 After I move/reorder my collection I always set xyz back to the original selection.在我移动/重新排序我的收藏后,我总是将 xyz 设置回原始选择。

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

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