在UI线程上执行长任务

时间:2013-04-16 07:12:48

标签: c# wpf xaml user-interface binding

我正在开发一个简单的自定义控件,它应该充当菜单系统。它由2个按钮组成:Back和Home以及上面的菜单项。 ControlTemplate看起来像这样:

  <ControlTemplate x:Key="FancyColorPickerTemplate">
        <menu:BusyDecorator x:Name="BusyDecorator"  Style="{StaticResource BusyDecoratorStyle}">
            <menu:BusyDecorator.IsBusyIndicatorShowing>
                <PriorityBinding>
                    <Binding Path="IsBusy" RelativeSource="{RelativeSource AncestorType={x:Type CustomControls:Menu}}"/>
                </PriorityBinding>
            </menu:BusyDecorator.IsBusyIndicatorShowing>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="0.70*"/>
                    <RowDefinition Height="0.30*"/>
                </Grid.RowDefinitions>

                <ItemsControl Grid.Row="0" Name="Part_ItemControl" 
                        ItemTemplateSelector="{StaticResource imgStringTemplateSelector}"
                          HorizontalAlignment="Center" VerticalAlignment="Center">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <WrapPanel Orientation="Horizontal"/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                </ItemsControl>
                <Button  Grid.Row="1" Name="PART_BackButton"  FontSize="20" Content="Back" HorizontalAlignment="Left" />
                <Button  Grid.Row="1" Name="PART_HomeButton"  FontSize="20" Content="Home" HorizontalAlignment="Center" />
            </Grid>
        </menu:BusyDecorator>
    </ControlTemplate>

在ItemsControl上有一个ItemTemplateSelector来选择所显示元素的DataTemplate(可以是一个按钮,也可以是一个UserControl)。 示例:

    <DataTemplate x:Key="ButtonTemplate">
        <Grid Margin="10,0,10,0">
            <Button Content="{Binding Title}" ></Button>
          </Grid>
    </DataTemplate>

    <DataTemplate x:Key="UserControlTemplate">
        <Grid Margin="10,0,10,0">
            <CustomControls:ColorPickerUserControl Width="200"   Height="200"/>
        </Grid>
    </DataTemplate>

在Codebehind中,我检查点击了哪个元素并加载子菜单(通过设置ItemsControl的ItemsSource属性),如果需要:

 void Menu_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        ItemsControl itemsControl = GetTemplateChild("Part_ItemControl") as ItemsControl;
        object item = GetElementFromPoint(itemsControl, e.GetPosition(itemsControl));

        if (item != null && item is MenuItem2)
        {
            MenuItem2 mi = item as MenuItem2;
            if (mi.SubMenu != null)
            {
                IsBusy = true;
                Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                 {
                     MenuItems = new ObservableCollection<MenuItem2>(mi.SubMenu.Items);
                     IsBusy = false;
                 }));
                m_MenuStack.Push(mi.SubMenu);
            }
            else
            {
                if (!IsBusy)
                {
                    ExecuteAction(mi.Ac);
                }
            }
        }
        else
            Console.WriteLine("no item found");
    }

上面代码中的MenuItem绑定到ItemsSource属性,该属性将重新评估ItemsControl并根据DataTemplateSelector应用相应的DataTemplate。 我的代码中的问题是上面的IsBusy属性应该显示BusyDecorator(参见xaml),而DataTemplate是一个需要很长时间才能显示的UserControl。它不起作用,因为我猜UserControl正在UI线程上加载,以及IsBusy属性触发UI线程上的操作。

我是否采取了错误的做法?有没有办法让这项工作?

1 个答案:

答案 0 :(得分:0)

您可以随时设置忙标志,并在忙集的渲染完成后在UI线程上安排其余的工作。

这里神奇的部分是使用优先级System.Windows.Threading.DispatcherPriority.Render来调度线程,这使得任务在渲染的同时运行。

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Button Click="Button_Click_1">LongTask</Button>
        <TextBlock Grid.Row="1" Text="{Binding IsBusy}"/>
    </Grid>
</Window>

和背后的代码

using System;
using System.Threading;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public bool IsBusy
        {
            get { return (bool)GetValue(IsBusyProperty); }
            set { SetValue(IsBusyProperty, value); }
        }

        public static readonly DependencyProperty IsBusyProperty = DependencyProperty.Register("IsBusy", typeof(bool), typeof(MainWindow), new PropertyMetadata(false));

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            IsBusy = true;
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                Thread.Sleep(2000);

                IsBusy = false;
            }), System.Windows.Threading.DispatcherPriority.Render, null);
        }
    }
}