ObservableCollection and ListBoxItem DataTemplate generation problem

后端 未结 3 1330
余生分开走
余生分开走 2021-01-15 05:55

Something strange is going on with ObservableCollection.

I have the following code:

private readonly ObservableCollection _displa         


        
相关标签:
3条回答
  • 2021-01-15 06:21

    The wpf layout engine won't have been through the layout and arrange pass so your listboxitems won't have been given a size yet. Sticking in the message box will allow the background threads that do this run. Try forcing a call to Measure() on your items before looking at their size.

    0 讨论(0)
  • 2021-01-15 06:21

    SOLVED

    This creates somewhat flickering effect for a fraction of second (as if loading items one by one), but actually suits my needs.

    The point is to refresh the UI for an item before retrieving its height.

    I have created an extension method:

        public static void RefreshUI(this DependencyObject obj)
        {
            obj.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Loaded, (Action)delegate { });
        }
    

    And then before retrieving the height, I refresh the UI.

    private double CalculateItemsHeight(int index)
        {
            ListBoxItem lbi = _box.ItemContainerGenerator.ContainerFromIndex(index) as ListBoxItem;
            if (lbi != null) {
                lbi.RefreshUI();
                return lbi.ActualHeight;
            }
            return 0;
        }
    
    0 讨论(0)
  • 2021-01-15 06:28

    Actually, I was trying to get this to work and I found the ".UpdateLayout()" function, which works perfectly for me. I realize that you're doing vertical and I'm doing horizontal, but here's my code, it's pretty simple:

    for (int i = 0; i < listOfItems.ItemsIn.Count; ++i)
        {
            //CalculateItemsHeight(i);
    
            ListBoxItem abc = (lb.ItemContainerGenerator.ContainerFromItem(lb.Items[i]) as ListBoxItem);
            abc.UpdateLayout();
            totalWidth += abc.ActualWidth;
        }
    

    Hopefully this helps!

    0 讨论(0)
提交回复
热议问题