How can I check when the databinding of a list is

2020-07-18 09:55发布

问题:

I have a pivot control where its item contains a listbox with items. When I scroll to the next pivot item the data binding takes some time, and I want to know when the data binding is complete because I need to enable the menu bar, as soon as the listbox is ready to appear. I couldn't find an event that can help me here. I tried the Loaded event of the listbox but while it works for some pivot items, for some others it doesn't fire! I also tried the layout updated event but it is fired too many times and it can't help me.

What could i do? thank you

回答1:

To ensure good performance when quickly scrolling through pivot items, you should wait to bind the contents of a pivot item until the SelectedIndex changes. That way it won't try to bind while the user is quickly swiping between Pivot items; it will only bind when you stop on a Pivot item.

You should then set the ItemsSource property of the ListBox in your Pivot item in the LayoutUpdated event. I use the following extension method:


        public static void InvokeOnLayoutUpdated(this FrameworkElement element, Action action)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            else if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            // Create an event handler that unhooks itself before calling the
            // action and then attach it to the LayoutUpdated event.
            EventHandler handler = null;
            handler = (s, e) =>
            {
                element.LayoutUpdated -= handler;
                action();
            };
            element.LayoutUpdated += handler;
        }

So you would then have some code that looked something like this:


pivot.InvokeOnLayoutUpdate(() =>
  {
    Dispatcher.BeginInvoke(() => 
      {
        list.ItemsSource = source;
        ApplicationBar.IsMenuEnabled = true;
      });
  });