首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >初始化BusyIndicator时显示UserControls (WPF + Mvvm + DataTemplate应用程序)

初始化BusyIndicator时显示UserControls (WPF + Mvvm + DataTemplate应用程序)
EN

Stack Overflow用户
提问于 2016-02-28 16:07:29
回答 2查看 1.2K关注 0票数 0

现状

我使用以下方法解析匹配ViewModel的视图。(简化)

代码语言:javascript
复制
<Window.Resources>
    <ResourceDictionary>
        <DataTemplate DataType="{x:Type local:DemoVm2}">
            <local:DemoViewTwo />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:DemoVm}">
            <local:DemoView />
        </DataTemplate>
    </ResourceDictionary>
</Window.Resources>

<DockPanel LastChildFill="True">
    <Button Content="Switch To VmOne" Click="ButtonBase_OnClick"></Button>
    <Button Content="Switch To VmTwo" Click="ButtonBase_OnClick2"></Button>

    <ContentPresenter Content="{Binding CurrentContent}" />
</DockPanel>

视图在切换ViewModel后由ContentPresenter自动解析。

当使用复杂视图时,初始化可能需要2-4秒,我想显示一个BusyIndicator。因为视觉的数量而不是数据,它们需要2-4秒的时间。

问题

我不知道视图什么时候完成了初始化/加载过程,因为我只能访问当前的ViewModel。

My approach

我的想法是在每个UserControl上附加一个行为,在InitializeComponent()完成或处理它们的LoadedEvent之后,该行为可以将布尔值设置为附加的InitializeComponent (IsBusy=false)。此属性可以绑定到其他地方的BusyIndicator。

我对这个解决方案并不满意,因为我需要将这个行为附加到每个单独的Usercontrol/视图中。

有谁有解决这种问题的办法吗?我想我不是唯一一个想要向用户隐藏GUI加载过程的人?!

最近我遇到了一个线程http://blogs.msdn.com/b/dwayneneed/archive/2007/04/26/multithreaded-ui-hostvisual.aspx。但既然这是从2007年开始,也许还有更好/更方便的方法来实现我的目标呢?

EN

回答 2

Stack Overflow用户

发布于 2016-02-28 20:48:51

这个问题没有简单和普遍的解决办法。在每种具体情况下,您都应该编写自定义逻辑,以实现非阻塞的视觉树初始化。

下面是一个使用初始化指示器实现ListView非阻塞初始化的示例。

包含UserControl和初始化指示符的ListView:

XAML:

代码语言:javascript
复制
<UserControl x:Class="WpfApplication1.AsyncListUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApplication1"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid Margin="5" Grid.Row="1">
        <ListView x:Name="listView"/>
        <Label x:Name="itemsLoadingIndicator" Visibility="Collapsed" Background="Red" HorizontalAlignment="Center" VerticalAlignment="Center">Loading...</Label>
    </Grid>
</UserControl>

政务司司长:

代码语言:javascript
复制
public partial class AsyncListUserControl : UserControl
{
    public static DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(IEnumerable), typeof(AsyncListUserControl), new PropertyMetadata(null, OnItemsChanged));

    private static void OnItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        AsyncListUserControl control = d as AsyncListUserControl;
        control.InitializeItemsAsync(e.NewValue as IEnumerable);
    }

    private CancellationTokenSource _itemsLoadiog = new CancellationTokenSource();
    private readonly object _itemsLoadingLock = new object();

    public IEnumerable Items
    {
        get
        {
            return (IEnumerable)this.GetValue(ItemsProperty);
        }
        set
        {
            this.SetValue(ItemsProperty, value);
        }
    }

    public AsyncListUserControl()
    {
        InitializeComponent();
    }

    private void InitializeItemsAsync(IEnumerable items)
    {
        lock(_itemsLoadingLock)
        {
            if (_itemsLoadiog!=null)
            {
                _itemsLoadiog.Cancel();
            }

            _itemsLoadiog = new CancellationTokenSource();
        }

        listView.IsEnabled = false;
        itemsLoadingIndicator.Visibility = Visibility.Visible;
        this.listView.Items.Clear();

        ItemsLoadingState state = new ItemsLoadingState(_itemsLoadiog.Token, this.Dispatcher, items);

        Task.Factory.StartNew(() =>
        {
            int pendingItems = 0;
            ManualResetEvent pendingItemsCompleted = new ManualResetEvent(false);

            foreach(object item in state.Items)
            {
                if (state.CancellationToken.IsCancellationRequested)
                {
                    pendingItemsCompleted.Set();
                    return;
                }

                Interlocked.Increment(ref pendingItems);
                pendingItemsCompleted.Reset();

                state.Dispatcher.BeginInvoke(
                    DispatcherPriority.Background,
                    (Action<object>)((i) =>
                    {
                        if (state.CancellationToken.IsCancellationRequested)
                        {
                            pendingItemsCompleted.Set();
                            return;
                        }

                        this.listView.Items.Add(i);
                        if (Interlocked.Decrement(ref pendingItems) == 0)
                        {
                            pendingItemsCompleted.Set();
                        }
                    }), item);
            }

            pendingItemsCompleted.WaitOne();
            state.Dispatcher.Invoke(() =>
            {
                if (state.CancellationToken.IsCancellationRequested)
                {
                    pendingItemsCompleted.Set();
                    return;
                }

                itemsLoadingIndicator.Visibility = Visibility.Collapsed;
                listView.IsEnabled = true;
            });
        });
    }

    private class ItemsLoadingState
    {
        public CancellationToken CancellationToken { get; private set; }
        public Dispatcher Dispatcher { get; private set; }
        public IEnumerable Items { get; private set; }

        public ItemsLoadingState(CancellationToken cancellationToken, Dispatcher dispatcher, IEnumerable items)
        {
            CancellationToken = cancellationToken;
            Dispatcher = dispatcher;
            Items = items;
        }
    }
}

用法示例:

代码语言:javascript
复制
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Button Content="Load Items" Command="{Binding LoadItemsCommand}" />
        <local:AsyncListUserControl Grid.Row="1" Items="{Binding Items}"/>
    </Grid>
</Window>

ViewModel:

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Input;

namespace WpfApplication1
{
    public class MainWindowViewModel:INotifyPropertyChanged
    {
        private readonly ICommand _loadItemsCommand;
        private IEnumerable<string> _items;

        public event PropertyChangedEventHandler PropertyChanged;

        public MainWindowViewModel()
        {
            _loadItemsCommand = new DelegateCommand(LoadItemsExecute);
        }

        public IEnumerable<string> Items
        {
            get { return _items; }
            set { _items = value; OnPropertyChanged(nameof(Items)); }
        }

        public ICommand LoadItemsCommand
        {
            get { return _loadItemsCommand; }
        }

        private void LoadItemsExecute(object p)
        {
            Items = GenerateItems();
        }

        private IEnumerable<string> GenerateItems()
        {
            for(int i=0; i<10000; ++i)
            {
                yield return "Item " + i;
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            var h = PropertyChanged;
            if (h!=null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public class DelegateCommand : ICommand
        {
            private readonly Predicate<object> _canExecute;
            private readonly Action<object> _execute;
            public event EventHandler CanExecuteChanged;

            public DelegateCommand(Action<object> execute) : this(execute, null) { }

            public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
            {
                _execute = execute;
                _canExecute = canExecute;
            }

            public bool CanExecute(object parameter)
            {
                if (_canExecute == null)
                {
                    return true;
                }

                return _canExecute(parameter);
            }

            public void Execute(object parameter)
            {
                _execute(parameter);
            }

            public void RaiseCanExecuteChanged()
            {
                if (CanExecuteChanged != null)
                {
                    CanExecuteChanged(this, EventArgs.Empty);
                }
            }
        }
    }
}

这一办法的主要特点是:

  1. 需要大量UI初始化的数据的自定义依赖项属性。
  2. DependencyPropertyChanged回调启动管理UI初始化的工作线程。
  3. Worker线程将执行优先级较低的小操作分派到UI线程中,这将使UI负责。
  4. 额外的逻辑,以保持一致的状态,以防初始化再次执行,而以前的初始化尚未完成。
票数 1
EN

Stack Overflow用户

发布于 2016-02-28 16:52:40

另一种方法是从UserControl隐藏和IsBusy开始。在Application.Dispatcher上的一个单独线程中启动加载。胎面的最后声明是IsBusy=false;UserControl.Visibility = Visibility.Visible;

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35684854

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档