【问题标题】:Update Binding in Windows Phone Runtime app更新 Windows Phone 运行时应用中的绑定
【发布时间】:2014-10-11 23:03:51
【问题描述】:

我正在尝试在我的 Windows Phone RunTime 应用上修改 ListView 中的一些项目。

Items 通过简单的绑定绑定到 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,而不会丢失它的滚动位置?

【问题讨论】:

    标签: c# listview windows-runtime windows-phone-8.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();
                }
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      您应该使用ObservableCollection&lt;myItem&gt; 而不是List&lt;myItem&gt;。然后你就不需要取消设置和设置列表来更新 ListView。

      要滚动到带有ListView listView 的ListView 中的项目,您可以调用listView.ScrollIntoView(item)。

      【讨论】:

      • 很抱歉,我无法让ScrollIntoView 工作。 myListView.ScrollIntoView(pi[7]); 和 myListView.ScrollIntoView(myListView.Items[7]); 都不起作用。你能帮忙吗?
      • 在调用 ScrollIntoView 之前尝试添加 listView.UpdateLayout()
      • 哦。对不起。我错过了你关于ObservableCollection 的观点。使用ObservableCollection,我不需要再次将绑定设置为null 和pi。所以我根本不需要ScrollIntoView。它会自动完成所有工作。谢谢你:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多