WPF: How to bind a command to the ListBoxItem using MVVM?

后端 未结 4 684
栀梦
栀梦 2020-12-01 04:53

I have just started learning MVVM. I\'ve made the application from scratch by following this MVVM tutorial (I highly recommend it to all MVVM beginners out there). Basically

4条回答
  •  醉酒成梦
    2020-12-01 05:29

    I find the best way to do this is to create a simple user control wrapper for my content, with dependency properties for the command and parameter.

    The reason I did this was due to the Button not bubbling the click event to my ListBox which prevented it from selecting the ListBoxItem.

    CommandControl.xaml.cs:

    public partial class CommandControl : UserControl
    {
        public CommandControl()
        {
            MouseLeftButtonDown += OnMouseLeftButtonDown;
            InitializeComponent();
        }
    
        private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs)
        {
            if (Command != null)
            {
                if (Command.CanExecute(CommandParameter))
                {
                    Command.Execute(CommandParameter);
                }
            }
        }
    
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.Register("Command", typeof(ICommand),
                typeof(CommandControl),
                new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None));
    
        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }
    
        public static readonly DependencyProperty CommandParameterProperty =
            DependencyProperty.Register("CommandParameter", typeof(object),
                typeof(CommandControl),
                new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None));
    
        public object CommandParameter
        {
            get { return (object)GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }
    }
    

    CommandControl.xaml:

    
    
    

    Usage:

    
        
            
        
    
    

    The Content can be whatever, and when the control is clicked, it will execute the command.

    EDIT: Added Background="Transparent" to UserControl to enable click events on the entire area of the control.

提交回复
热议问题