32

I looked over this web and google and the solutions didn't work for me.

I have a command on the ViewModel of a UserControl. Well, The usercontrol have a ItemsControl binded to a ObservableCollection. Inside the DataTemplate of the ItemsControl.ItemTemplate I have a button and I want to use the command. I can't bind the command because inside the DataTemplate, the datacontext is not the ViewModel but an item of the ObservableCollection.

The question is: How can I bind the button to the command if a lost the parent datacontext?

I think that this need to have an easy solution because I think that this is a common problem.

Imagine this sceneario:

You have a ListBox item with an observableCollection as the ItemsSource, so you are using a datatemplate inside the ListBox for every element in the collection. Well, you want to delete the selected item and you put a button in every row for that job. ¿How do you do that?

In MVP, I can do this in the click event of the button:

Button but = e.Source as Button;

if (but != null)
      Presenter.ActualNote = but.DataContext as Note;

In short. You send the datacontext of the row (the selected item) to the presenter.

But, how can I do it in the mvvm way? Because I need to use a command but I can't assign the command to the button because the button does know nothing about the ViewModel (where the command exists).

As you can see, the button has to exist inside the datatemplate, then the datacontext is not the ViewModel anymore.... There is why I need to access to the parent's DataContext, for access to the command.

I hope that you understand my problem better.

Thank you.

Matt
  • 74,352
  • 26
  • 153
  • 180
Jesus Rodriguez
  • 11,918
  • 9
  • 64
  • 88

4 Answers4

91

Use the binding below for your button's command:

{Binding DataContext.CommandName, 
         RelativeSource={RelativeSource FindAncestor, 
                         AncestorType={x:Type MyUserControl}}}

This will tell it to find your UserControl and use its DataContext.

Indy9000
  • 8,651
  • 2
  • 32
  • 37
Eddie Deyo
  • 5,200
  • 8
  • 35
  • 35
  • That's is the solution I found but It doesn't work for me. If a put: Command="{Binding DataContext.CommandName, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" Its says that AncestorType should be specified for RelativeSource on the FindAncestor mode. Where is the problem? Thanks for the answer. – Jesus Rodriguez Jun 15 '09 at 20:50
  • 1
    I just tried this in a sample and it worked for me. It sounds like a syntax error. Can you copy and paste your button's XAML? – Eddie Deyo Jun 16 '09 at 14:20
  • Oh, there is no error, VS marked it but it compiles. Im trying know with something simple. I put a Tag element in the usercontrol and I want to print it en in the header of a menuitem: . But, visual studio say: Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''. BindingExpression:Path=Tag; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Header' (type 'Object' – Jesus Rodriguez Jun 16 '09 at 15:21
  • Instead of putting UserControl for your type, try putting the type of your control. So you would have {x:Type ctrl:MyControl}, if your control was called MyControl and you've mapped xmlns:ctrl to its namespace. – Eddie Deyo Jun 16 '09 at 15:38
  • +1! Great, this worked finally after an approach with the `ElementName` failed. – Sören Feb 28 '11 at 12:47
  • 2
    Great, works like a charm! As a side-note: if you still wish to preserve the data context of the button to pass to the command binding, use CommandParameter="{Binding Path=.}" That way the parameter object is the context of the control. – Simon Mattes Nov 18 '14 at 14:50
  • it says myusercontrol is not existing – Isuru Herath May 09 '15 at 19:51
5

If you want a dirty, MVVM-breaking solution, then set the Tag="{Binding}" on the button and handle the Click event. In the event handler, call the command on your ViewModel.

geofftnz
  • 9,954
  • 2
  • 42
  • 50
3

Ok, then what about modifying your data item class so that it has a property referencing to the whole model view?

If your ItemsSource is of type ObservableCollection<DataItem> then modify DataItem type like this:

public class DataItem
{
    public BusinessObject Value { get; set; }

    private ModelView modelView;

    public ModelView ModelView
    {
        get
        {
            return modelView;
        }
    }

    public DataItem(ModelView modelView)
    {
        this.modelView = modelView;
    }
}
Dmitry Tashkinov
  • 1,976
  • 19
  • 16
2

RelativeSource works, but I don't think it's right to let controls to prowl across each other's properties. It is strange that button placed inside an item view does something with an outer data source rather than with the bound item. You might need to review the program code’s design.

Dmitry Tashkinov
  • 1,976
  • 19
  • 16
  • I like your answer but I need that for this solution. I have a itemscontrol with a grid inside, every item is a note. Well, I have a context menu in the grid that have some options about the "selected" note. Every option is a command but the menu's datacontext is the actual note an not the viewmodel. I cant put the menu outside because I need the menu for each item. – Jesus Rodriguez Jun 15 '09 at 21:09
  • Hm, yes, don't think it's an ideal solution, but you can place your ModelView object as a static resorce into a Window.Resources element, maybe using ObjectDataProvider, and then reference it by Static extension inside any data binding from any part of the window. – Dmitry Tashkinov Jun 16 '09 at 06:27
  • I agree -- it's always felt like a hack when I've used this solution -- but a hack that works. ;) – Eddie Deyo Jun 16 '09 at 14:04