【问题标题】:Virtualization seems to be messing up binded properties虚拟化似乎弄乱了绑定的属性
【发布时间】:2017-06-24 12:02:40
【问题描述】:

我有一个列表视图,作为数据模板,它有一个相对复杂的用户控件,并绑定了几个属性。

ItemsPanel 如下:

<ListView.ItemsPanel>
     <ItemsPanelTemplate>
          <ItemsStackPanel VerticalAlignment="Bottom" ItemsUpdatingScrollMode="KeepLastItemInView"/>
      </ItemsPanelTemplate>
</ListView.ItemsPanel>

我的列表视图通常包含大约 70 个项目,但是我遇到了一个相当大的问题:

每次我向上滚动大约 30 个项目然后再向下滚动时,属性似乎变得混乱,其中一些似乎与更高项目的属性切换。

例如,如果之前我有以下情况:

  • 属性 A = 1
  • 属性 A = 2
  • 属性 A = 3

上下滚动后,我会:

  • 属性 A = 1
  • 属性 A = 2
  • 属性 A = 1

如何确保项目保持其属性或正确重新加载?

【问题讨论】:

  • 如果你阻止虚拟化会有什么结果?你有一个minimal reproducible example项目在我们这边测试吗?
  • 我无法重现此问题。正如@SunteenWu-MSFT 所说 - 你应该提供一个 MCVE(你可能会在它时查明问题)。

标签: c# data-binding uwp dependency-properties virtualization


【解决方案1】:

我终于想出了如何解决这个问题:如果其他人遇到了类似的问题,这可能是因为您正在处理 PropertyChanged 事件而没有重置丢失或为空的属性。例如,如果这是列表视图的数据模板内的用户控件:

&lt;local:CustomControl CustomText={Binding text}/&gt;

它的处理方式是这样的:

    public string CustomText        
    {
        get { return (string)GetValue(CustomTextProperty); }
        set { SetValue(CustomTextProperty, value); }
    }
    public static readonly DependencyProperty CustomTextProperty = DependencyProperty.Register(
        nameof(CustomText),
        typeof(string),
        typeof(CustomControl),
        new PropertyMetadata(string.Empty, OnPropertyChanged));

    private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var instance = d as CustomControl;
        if(instance.CustomText != "") 
            myTextBlock.Text = instance.CustomText;
    }

每次虚拟化回收 CustomControl 时,如果它被绑定到一个空字符串,由于if(instance.CustomText != ""),文本块将不会更新,并且旧属性将再次显示。如果由于某种原因从未调用 OnPropertyChanged,也会发生同样的情况。

在这种特殊情况下看起来有点愚蠢,但在具有大量属性和子属性的大型用户控件上可能会变得相当混乱

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    相关资源
    最近更新 更多