Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF binding error with ICommand

I have a simple WPF example trying to bind a ListBox's Selected event to an ICommand in the view model.

XAML

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">
    <Grid>
        <ListBox ItemsSource="{Binding Items}" 
                 Selected="{Binding DoSomething}"/>

    </Grid>
</Window>

View Model

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = new ViewModel();
        }
    }

    public class ViewModel : INotifyPropertyChanged
    {
        public ViewModel()
        {
            Items = new List<string>();
            Items.Add("A");
            Items.Add("B");
            Items.Add("C");

            DoSomething = new MyCommand();
        }

        public List<string> Items { get; set; }


        public event PropertyChangedEventHandler PropertyChanged;

        public ICommand DoSomething { get; set; }
    }

    public class MyCommand : ICommand
    {
        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter) { return true; }

        public void Execute(object parameter) { }
    }
}

The error occurs in the constructor on InitializeComponent.

XamlParseException: A 'Binding' cannot be set on the 'AddSelectedHandler' property of type 'ListBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

enter image description here

How can I have an ICommand called in my view model from the Selected event of a ListBox control?

like image 651
John Livermore Avatar asked Feb 23 '26 18:02

John Livermore


1 Answers

Selected on a ListBox is an event. You have the SelectedItem which you can bind to a property of the same type as an element of the list on the viewmodel:

<Grid>
    <ListBox ItemsSource="{Binding Items}" 
             SelectedItem="{Binding MyItem}"/>
</Grid>

.

public class ViewModel : INotifyPropertyChanged
{
    public string MyItem { get; set; }
}

As for your command, you need a control which handles a CommandSource, like the Button:

<Button Command="{Binding DoSomething}" CommandParameter="{Binding}" />

Binding it like this, will enable WPF to recognize your ICommand. The CommandParameter is optional though.

like image 175
Seb Avatar answered Feb 25 '26 07:02

Seb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!