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

后端 未结 4 748
一个人的身影
一个人的身影 2020-12-25 12:50

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 ItemsContro

相关标签:
4条回答
  • 2020-12-25 12:57

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-25 12:58

    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.

    0 讨论(0)
  • 2020-12-25 13:04

    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.

    0 讨论(0)
  • 2020-12-25 13:08

    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.

    0 讨论(0)
提交回复
热议问题