views:

313

answers:

2

Hi

I am using MVVM light to bind events on UIElements in my View to ICommands in my view model, and this is working very well.

However - I have a situation where I have to create some controls on the fly, and I'm doing this in the code behind on the view as this seems the best place to do it, and it is after all UI code. As I am generating these controls in the code, I also need to create the event bindings in the code and, despite several attempts, I have not acheived the desired result.

Has anybody done this or does anybody know how to?

Any help appreciated!

A: 

I do not know MVVM Light but assuming that your viewmodel is set as the DataContext of your view there are at least the following two options.

  1. If you know the type of the viewmodel attached to your view, you can access the commands of the viewmodel directly and there is no need to use binding as you can set the Command property directly:

    var buttonA = new Button();
    buttonA.Content = "Click me";
    buttonA.Command = (DataContext as TheViewModel).TheCommand;
    
  2. If you do not know the type of your viewmodel you can create a binding in the following way:

    var buttonB = new Button();
    buttonB.Content = "Click me too";
    var binding = new Binding("TheCommand");
    binding.Source = DataContext;
    buttonB.SetBinding(Button.CommandProperty, binding);
    
Jakob Christensen
I believe the question is more about how to add the EventToCommand attached property included in the MVVM Light Toolkit through code instead of XAML.
Matt Casto
I think you are right. I guess my answer isn't of much use then :-|
Jakob Christensen
A: 

Hi - thanks for your answers and comments. Matt is right - the question is about how to use EventToCommand in code instead of XAMl. Matt - I do need to generate the controls at runtime because I never know until that point what the controls will be. The controls are on a ribbon, and the ribbon is context sensitive, i.e. whenever the main view is changed the controls on the ribbon change with it and need to be generated.

I have found a solution using attached properties, but I would still like to know how (and if) this can be done with MVVM Light.

Sean
Hi Sean - welcome to StackOverflow. You should post this comment as an edit to your question - it's elaboration, rather than an answer, and it belongs with your original question. Regarding your comment, though: it's still possible to generate your context-sensitive changes on the ribbon through pure Xaml and clever use of data templates. I would advise against doing it in code, since it limits your flexibility and makes the Xaml more tightly-bound to its codebehind (which is something you rarely need to do in WPF).
Dan Puzey
If you edit your original question to ask for examples of how this can be done, I'm sure someone will answer (sadly I haven't got time right now, but I'll come back to check later!).
Dan Puzey