与ICommand的WPF绑定错误

Joh*_*ore 4 c# data-binding wpf xaml

我有一个简单的WPF示例尝试将ListBox的Selected事件绑定到视图模型中的ICommand.

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>
Run Code Online (Sandbox Code Playgroud)

查看模型

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) { }
    }
}
Run Code Online (Sandbox Code Playgroud)

该错误发生在InitializeComponent上的构造函数中.

XamlParseException:无法在"ListBox"类型的"AddSelectedHandler"属性上设置"绑定".'绑定'只能在DependencyObject的DependencyProperty上设置.

在此输入图像描述

如何从ListBox控件的Selected事件中在我的视图模型中调用ICommand?

Seb*_*Seb 5

在ListBox上选择是一个事件.您有SelectedItem,您可以将其绑定到与viewmodel上列表元素相同类型的属性:

<Grid>
    <ListBox ItemsSource="{Binding Items}" 
             SelectedItem="{Binding MyItem}"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)

.

public class ViewModel : INotifyPropertyChanged
{
    public string MyItem { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

至于你的命令,你需要一个处理CommandSource的控件,比如Button:

<Button Command="{Binding DoSomething}" CommandParameter="{Binding}" />
Run Code Online (Sandbox Code Playgroud)

像这样绑定它将使WPF能够识别您的ICommand.CommandParameter是可选的.