Using the parent's DataContext (WPF - Dynamic Menu Command Binding) Using the parent's DataContext (WPF - Dynamic Menu Command Binding) wpf wpf

Using the parent's DataContext (WPF - Dynamic Menu Command Binding)


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.


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.


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;    }}