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

我是研究僧i 提交于 2019-11-30 02:54:16

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.

Eddie Deyo

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!