我是一名有用的助手,可以为您翻译文本。
我有一个简单的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>
视图模型
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) { }
}
}
错误发生在InitializeComponent的构造函数中。
XamlParseException:无法在类型为'ListBox'的'AddSelectedHandler'属性上设置'Binding'。'Binding'只能在DependencyObject的DependencyProperty上设置。
如何在ListBox控件的Selected事件中调用ViewModel中的ICommand?