在Windows Phone运行时应用程序中更新绑定

时间:2014-08-18 23:02:52

标签: c# listview windows-runtime windows-phone-8.1

我尝试修改Windows Phone RunTime应用中ListView的某些项目。

通过简单的绑定将项目绑定到ListView:

this.defaultViewModel["myBinding"] = pi;

和xaml:

<ListView ItemsSource="{Binding myBinding}" ... >

然后,我正在修改代码中的绑定:

        List<myItem> pi = (List<myItem>)this.defaultViewModel["myBinding"];
        pi.RemoveAt(5);

现在,我想使用新修改的pi更新UI。我知道this.defaultViewModel["myBinding"] = null;然后this.defaultViewModel["myBinding"] = pi;有效,但它不会保持ListView的滚动位置(在执行此操作后会跳到顶部)。

此外,我尝试了this answer,但似乎UpdateTarget在Windows Phone RunTime应用中不可用。

那么,我该如何强制刷新ItemsSource ListView,而不会丢失它的滚动位置?

2 个答案:

答案 0 :(得分:2)

您应该使用ObservableCollection<myItem>代替List<myItem>。然后,您不需要取消设置并设置列表以更新ListView。

要使用ListView listView滚动到ListView中的项目,您可以拨打listView.ScrollIntoView(item)

答案 1 :(得分:1)

需要实施INofityPropertyChanged

MSDN: inotifypropertychanged Example

MSDN文章中的示例:

public class DemoCustomer : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    // This method is called by the Set accessor of each property. 
    // The CallerMemberName attribute that is applied to the optional propertyName 
    // parameter causes the property name of the caller to be substituted as an argument. 
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private DemoCustomer()
    {
    }

    private string customerNameValue = String.Empty;
    public string CustomerName
    {
        get
        {
            return this.customerNameValue;
        }

        set
        {
            if (value != this.customerNameValue)
            {
                this.customerNameValue = value;
                NotifyPropertyChanged();
            }
        }
    }
}