0

现在的情况

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

<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>

在 ContentPresenter 内切换 ViewModel 后,WPF 会自动解析视图。

当使用可能需要 2-4 秒进行初始化的复杂视图时,我想显示一个 BusyIndi​​cator。由于视觉效果而非数据量,它们最多需要 2-4 秒。

问题

我不知道 View 何时完成初始化/加载过程,因为我只能访问当前的 ViewModel。

我的方法

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

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

有没有人对这种问题有另一种解决方案?我想我不是唯一一个想要对用户隐藏 GUI 加载过程的人?!

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

4

2 回答 2

1

这个问题没有简单和通用的解决方案。在每种具体情况下,您都应该为非阻塞可视化树初始化编写自定义逻辑。

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

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

XAML:

<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>

CS:

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;
        }
    }
}

使用示例:

<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>

视图模型:

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. 工作线程将执行优先级低的小动作分派到 UI 线程,由 UI 负责。

  4. 用于保持一致状态的附加逻辑,以防在先前的初始化尚未完成时再次执行初始化。

于 2016-02-28T20:48:51.027 回答
-1

另一种方法是从隐藏的 UserControl 和设置为 true 的 IsBusy 开始。在 Application.Dispatcher 上的单独线程中开始加载。胎面的最后语句是 IsBusy=false; UserControl.Visibility = Visibility.Visible;

于 2016-02-28T16:52:40.770 回答