Предварительный просмотрcanexecuteevent не выполнен

StackOverflow https://stackoverflow.com/questions/435101

  •  10-07-2019
  •  | 
  •  

Вопрос

У меня проблема с моей программой WPF.Я пытаюсь создать объект, который добавит обработчики ко всем элементам управления в одной и той же области.

Следующая строка не работает.Событие не обрабатывается.

element.AddHandler(CommandManager.PreviewCanExecuteEvent, new CanExecuteRoutedEventHandler(scope.CanExecutedHandler), true);

У меня также есть Команда, привязанная к кнопке.Итак, идея заключается в том, что я хочу, чтобы CanExecute выполнял команду для запуска:Это работает нормально.Мне также нужен обработчик для PreviewCanExecute:Это не сработает.

Мне жаль, что я не могу объяснить лучше.

Смотрите мой код ниже:

XAML:

<Window.Resources>
    <my:PermissionScope x:Key="permissionManager"/>
</Window.Resources>
<StackPanel>
    <TextBox Height="23" Name="textBox1" Width="120" />
    <Button Content="Permission Required" Command="{Binding Path=PermissionRequired}" my:PermissionScope.SharedPermissionScope="{StaticResource permissionManager}"/>
    <Button Content="Permission not required" Command="{Binding Path=PermissionRequired}"/>
</StackPanel>

PermissionScope.cs

public class PermissionScope
{

    public static readonly DependencyProperty SharedPermissionScopeProperty =
        DependencyProperty.RegisterAttached("SharedPermissionScope", typeof(PermissionScope), typeof(PermissionScope),
        new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits,
        new PropertyChangedCallback(OnUseGlobalSharedPermissionScopeChanged)));

    public static void SetSharedPermissionScope(DependencyObject depObj, PermissionScope scope)
    {
        // never place logic in here, because these methods are not called when things are done in XAML
        depObj.SetValue(SharedPermissionScopeProperty, scope);
    }

    public static PermissionScope GetSharedPermissionScope(DependencyObject depObj)
    {
        // never place logic in here, because these methods are not called when things are done in XAML
        return depObj.GetValue(SharedPermissionScopeProperty) as PermissionScope;
    }

    private static void OnUseGlobalSharedPermissionScopeChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs args)
    {
        if (depObj is Button)
        {
            if (args.OldValue != null)
            {
                RemoveEventHandlers(depObj as UIElement, args.OldValue as PermissionScope);
            }
            if (args.NewValue != null)
            {
                AttachEventHandlers(depObj as UIElement, args.NewValue as PermissionScope);
            }
        }
    }

    private static void AttachEventHandlers(UIElement element, PermissionScope scope)
    {
        if (element != null && scope != null)
        {
            element.AddHandler(CommandManager.PreviewCanExecuteEvent, new CanExecuteRoutedEventHandler(scope.CanExecutedHandler), true); // we need to see all events to subvert the built-in undo/redo tracking in the text boxes
        }
    }

    private static void RemoveEventHandlers(UIElement element, PermissionScope scope)
    {
        if (element != null && scope != null)
        {
            element.AddHandler(CommandManager.PreviewCanExecuteEvent, new CanExecuteRoutedEventHandler(scope.CanExecutedHandler));
        }
    }

    private void CanExecutedHandler(object sender, CanExecuteRoutedEventArgs e)
    {
        if (e.Command is CommandBase)
        {
            bool hasPermission = false;
            hasPermission = ((CommandBase)e.Command).HasPermission();

            ShowControl((UIElement)e.OriginalSource, hasPermission);
        }
    }

    public static void ShowControl(UIElement element, bool show)
    {
        element.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
    }
}

Я действительно ничем не могу помочь.

С наилучшими пожеланиями, Майкл

Это было полезно?

Решение

Я узнал себя.Это будет работать только с RoutedCommands, а не с ICommand

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top