带有自定义项模板的WPF上下文菜单在运行长时间命令时冻结

时间:2014-07-16 13:49:28

标签: wpf

我尝试使用自定义项模板动态生成上下文菜单。但是当用户运行一些长时间命令时,上下文菜单会在屏幕上冻结。如何避免上下文菜单冻结?

这是一个示例:

MainWindow.xaml:

<Window x:Class="MenuHangUpTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Width="525" Height="350">
    <Grid Width="500" Height="300">
        <TextBlock Text="Test test">
            <TextBlock.ContextMenu>
                <ContextMenu ItemsSource="{Binding ContextCommands}">
                    <ContextMenu.ItemContainerStyle>
                        <Style TargetType="{x:Type MenuItem}">
                            <Setter Property="Header" Value="{Binding Caption}" />
                            <Setter Property="Command" Value="{Binding Command}" />
                        </Style>
                    </ContextMenu.ItemContainerStyle>
                </ContextMenu>
            </TextBlock.ContextMenu>
        </TextBlock>
    </Grid>
</Window>

MainWindow.xaml.cs:

using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows;
using System.Windows.Input;

namespace MenuHangUpTest
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
        }

        public IEnumerable<TestCommandItem> ContextCommands
        {
            get
            {
                yield return new TestCommandItem();
            }
        }
    }

    public class TestCommandItem
    {
        public ICommand Command
        {
            get
            {
                return new TestCommand();
            }
        }

        public string Caption
        {
            get
            {
                return "Test";
            }
        }
    }

    public class TestCommand : ICommand
    {
        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            // context menu freezes on screen during running this command
            Thread.Sleep(5000);
            MessageBox.Show("Done!");
        }
    }
}

0 个答案:

没有答案
相关问题