我有一个简单的 WPF 示例,试图将 ListBox 的 Selected 事件绑定(bind)到 View 模型中的 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: A 'Binding' cannot be set on the 'AddSelectedHandler' property of type 'ListBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
如何从 ListBox 控件的 Selected 事件在我的 View 模型中调用 ICommand?
最佳答案
在 ListBox 上选择是一个事件。您有 SelectedItem,您可以将其绑定(bind)到与 View 模型上列表元素相同类型的属性:
<Grid>
<ListBox ItemsSource="{Binding Items}"
SelectedItem="{Binding MyItem}"/>
</Grid>
.
public class ViewModel : INotifyPropertyChanged
{
public string MyItem { get; set; }
}
至于您的命令,您需要一个处理 CommandSource 的控件,例如 Button:
<Button Command="{Binding DoSomething}" CommandParameter="{Binding}" />
像这样绑定(bind)它,将使 WPF 能够识别您的 ICommand。 CommandParameter 是可选的。
关于c# - 与 ICommand 的 WPF 绑定(bind)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49501216/