How to show a loading graphic/animation when wpf data binding is taking place

我是研究僧i 提交于 2019-12-18 14:58:08

问题


I have a WPF user control that contains a DataGrid. I'm binding an ObservableCollection of view models to it. Each view model has another collection of view models that I'm using to bind another DataGrid to. So the effect is a DataGrid with a nested DataGrid contained in the row details template.

Normally the binding is quite quick, but sometimes when there's a lot of data it can hang the UI while the binding/drawing is taking place.

Is there a way where I can either show a loading animation or progress bar while the binding/drawing is in progress?


回答1:


There's probably a more formal, or at least simpler solution, but you could use a modal popup window that is shown in a worker thread and is closed asynchronously when your is grid done loading:

Window waitWindow = new Window { Height = 100, Width = 200, WindowStartupLocation = WindowStartupLocation.CenterScreen, WindowStyle = WindowStyle.None };
waitWindow.Content = new TextBlock { Text = "Please Wait", FontSize = 30, FontWeight = FontWeights.Bold, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate
{
    Dispatcher.BeginInvoke(new Action(delegate { waitWindow.ShowDialog(); }));

    DataLoader dataLoader = new DataLoader(); // I made this class up
    dataLoader.DataLoaded += delegate
    {
        Dispatcher.BeginInvoke(new Action(delegate() { waitWindow.Close(); }));
    };

    dataLoader.LoadData();
};

worker.RunWorkerAsync();

You can replace the TextBlock with something pretty like a loading bar, and you could make the code re-usable by parameterizing the object that handles the loading of the grid(s) and passing it in to a commonly used method.

I hope that works for you.




回答2:


I had the same problem and this is how I solved it.

I discovered that DataGrid will only start creating controls when it displays the grid. In my case this was the time consuming process. After some tracing I found that creating the controls happens during measuring !

My solution is to override MeasureOverride and put the wait cursor around the base class call. I encapsulated my wait cursor setting in a class. So the code looks like this.

    protected override Size MeasureOverride(Size availableSize)
    {
        using (new DisposableWaitCursor(this))
        {
            return base.MeasureOverride(availableSize);
        }
    }



回答3:


You can use a wait cursor turned on/off using a data trigger.

I posted some code here.



来源:https://stackoverflow.com/questions/2114264/how-to-show-a-loading-graphic-animation-when-wpf-data-binding-is-taking-place

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!