从列表视图中删除选定的项目后,绑定不会更改

时间:2018-12-25 19:07:45

标签: c# forms xamarin

我正在编写xamarin表单应用程序,但是从SelectedItem绑定ListView时遇到问题。一切正常,直到从SelectedItem中删除ObservableCollection。此操作完成后,SelectedItem仍包含先前的值,但应等于null

为什么不起作用以及如何修复它。

    <ListView ItemsSource="{Binding Clients}" SelectionMode="Single" SelectedItem="{Binding SelectedSocket}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextCell Text="{Binding HostEntry.HostName}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

public ObservableCollection<TcpSocket> Clients { get; set; } = new ObservableCollection<TcpSocket>();
private TcpSocket _SelectedSocket { get; set; }
public TcpSocket SelectedSocket
{
    get => _SelectedSocket;
    set
    {
        _SelectedSocket = value;
        PropertyChanged(this, new PropertyChangedEventArgs(nameof(SelectedSocket)));
    }
}

在点击按钮后,类似的东西:

Clients.Remove(SelectedSocket);

1 个答案:

答案 0 :(得分:0)

将所需的属性从集合中删除后,将其手动设置为null,以便甚至可以更改更改的属性。

//...

public void OnClick(object sender, EventArgs e) {
    Clients.Remove(SelectedSocket); //raises collection changed
    SelectedSocket = null; //raises property changed
}

//...