2009-06-27 3 views
0

Я использую вспомогательные классы Julmar для WPF, так что я могу назвать обычай ICommand на события, такие как MouseEnter на текстовое поле, как так:Julmar WPF вспомогательные параметры

<TextBox Text="hmm"> 
    <julmar:EventCommander.Mappings>  
     <julmar:CommandEvent Command="{Binding DataContext.IncreaseQueueTimeCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" Event="MouseEnter" /> 
    </julmar:EventCommander.Mappings> 
</TextBox> 

Это работает и вызывает команду , проблема в том, что мне нужно передать объект в качестве параметра, знает ли кто-нибудь, возможно ли это? документация кажется довольно легкой.

Раньше я был в состоянии передать объект в качестве параметра, например так:

<Button Content="Save" x:Name="SaveQueueTimeButton" Command="{Binding DataContext.SaveQueueTimeCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" CommandParameter="{Binding}" /> 

Но очевидно, что это не то, что мне нужно, как это не срабатывает на MouseEvent

Любая помощь будет быть полезным,

Благодаря

ответ

1

Вы можете решить эту проблему с Behavior-шаблон. В основном вы создаете собственный класс с двумя свойствами зависимостей: Command и CommandParameter. Вы также регистрируете обработчик для обоих свойств.

В одном из обработчиков вы получаете свой TextBox, который передается как параметр. Теперь вы можете подключиться к событиям, которые вас интересуют. Если вызывается один из зарегистрированных обработчиков событий, вы можете вызвать связанную команду с параметром связанной команды.

Вот пример кода:

public class CommandHelper 
{ 
    // 
    // Attached Properties 
    // 
    public static ICommand GetCommand(DependencyObject obj) 
    { 
     return (ICommand)obj.GetValue(CommandProperty); 
    } 

    public static void SetCommand(DependencyObject obj, ICommand value) 
    { 
     obj.SetValue(CommandProperty, value); 
    } 

    public static readonly DependencyProperty CommandProperty = 
     DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(CommandHelper), new UIPropertyMetadata(null)); 



    public static object GetCommandParameter(DependencyObject obj) 
    { 
     return (object)obj.GetValue(CommandParameterProperty); 
    } 

    public static void SetCommandParameter(DependencyObject obj, object value) 
    { 
     obj.SetValue(CommandParameterProperty, value); 
    } 

    public static readonly DependencyProperty CommandParameterProperty = 
     DependencyProperty.RegisterAttached("CommandParameter", typeof(object), typeof(CommandHelper), new UIPropertyMetadata(null)); 


    // 
    // This property is basically only there to attach handlers to the control that will be the command source 
    // 
    public static bool GetIsCommandSource(DependencyObject obj) 
    { 
     return (bool)obj.GetValue(IsCommandSourceProperty); 
    } 

    public static void SetIsCommandSource(DependencyObject obj, bool value) 
    { 
     obj.SetValue(IsCommandSourceProperty, value); 
    } 

    public static readonly DependencyProperty IsCommandSourceProperty = 
     DependencyProperty.RegisterAttached("IsCommandSource", typeof(bool), typeof(CommandHelper), new UIPropertyMetadata(false, OnRegisterHandler)); 


    // 
    // Here you can register handlers for the events, where you want to invoke your command 
    // 
    private static void OnRegisterHandler(DependencyObject obj, DependencyPropertyChangedEventArgs e) 
    { 
     FrameworkElement source = obj as FrameworkElement; 

     source.MouseEnter += OnMouseEnter; 
    } 

    private static void OnMouseEnter(object sender, MouseEventArgs e) 
    { 
     DependencyObject source = sender as DependencyObject; 
     ICommand command = GetCommand(source); 
     object commandParameter = GetCommandParameter(source); 

     // Invoke the command 
     if (command.CanExecute(commandParameter)) 
      command.Execute(commandParameter); 
    } 
} 

И Xaml:

<TextBox Text="My Command Source" 
      local:CommandHelper.IsCommandSource="true" 
      local:CommandHelper.Command="{Binding MyCommand}" 
      local:CommandHelper.CommandParameter="MyParameter" /> 
+0

Не могли бы вы предоставить образец, пожалуйста? Мой мозг оказался в одном огромном узле после прочтения вашего описания. – chrischu

+0

Теперь вы можете найти пример кода выше. – Andrej

0

Если Julmar CommandEvent не обладает свойством CommandParameter, я предлагаю вам использовать Marlon Греча Attached Command Behaviours вместо этого. Он очень похож, но обладает свойством CommandParameter.

Смежные вопросы