2

I have clickable image/rectangle controls throughout my application and prefer to wire them in code:

clickableimagecontrol.MouseUp += MouseUp_Handler

I am struggling to understand how to do the same with datatemplates. I basically need to find the spot where the template is applied to each item, so I can insert my hooks.

I know WPF recommends using Commands of some type, but that requires more boiler-plate code, not to mention that image/rectangles don't support commands so I'd have to redo the whole thing with styled button controls instead.

Is this possible?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Jamona Mican
  • 1,574
  • 1
  • 23
  • 54
  • Doesn't seem possible. Using this reflection-based code to minimize command-based implementation boiler-plate seems the best compromise: http://nerobrain.blogspot.co.uk/2012/01/wpf-events-to-command.html Still about 10 lines of code for what should be doable in a couple though... – Jamona Mican Apr 18 '12 at 13:17
  • Wiring in code seems kind of pointless, what is the problem with using XAML? – H.B. Jul 23 '12 at 05:02

1 Answers1

1

Please see workable solution:

    private void ElementKeyUp(object source, KeyEventArgs args)
    {
        throw new NotImplementedException();
    }

    private DataTemplate GetDataTemplate()
    {
        var result = new DataTemplate();

        var factory = new FrameworkElementFactory(typeof(ListViewItem));

        var handler = new KeyEventHandler(ElementKeyUp);

        factory.AddHandler(KeyUpEvent, handler);

        result.VisualTree = factory;

        return result;
    }
Manushin Igor
  • 3,398
  • 1
  • 26
  • 40